have a polars dataframe. I wa doing some manipulations after which the column values are lists of some data types such as list of str or list of int. I want to those columns to be str or int. those lists only have one value in it so it should be easy right? How should I do it
Is this the best way to do it?
import polars as pl
# Sample DataFrame with multiple columns
df = pl.DataFrame({
"col1": [[1], [2], [3]], # list of int
"col2": [["a"], ["b"], ["c"]], # list of str
"col3": [[4], [5], [6]] # another list of int
})
# List of columns to convert
columns_to_convert = ["col1", "col2", "col3"]
# Apply the transformation to multiple columns
df = df.with_columns([
pl.col(col).arr.first().alias(col) for col in columns_to_convert
])
print(df)
is this compatible with lazyframe?
New contributor
Alan Chau is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.