To change the data types of columns within a DataFrame using Polars, you can use the cast
method.
Here's an example:
Assume you have a DataFrame df
with columns col1
and col2
of data types int64
and float64
, respectively, and you want to change col2
to a int64
data type.
import polars as pl
# Create a sample DataFrame
df = pl.DataFrame({
'col1': [1, 2, 3],
'col2': [1.0, 2.0, 3.0]
})
# Change col2 to int64 data type
df = df.lazy()
df = df.select([
pl.col('col1'),
pl.col('col2').cast(pl.Int64)
])
df = df.collect()
print(df)
Output:
shape: (3, 2)
┌───────┬───────┐
│ col1 ┆ col2 ┆
│ --- ┆ --- ┆
│ i64 ┆ i64 ┆
╞═══════╪═══════╡
│ 1 ┆ 1 ┆
│ 2 ┆ 2 ┆
│ 3 ┆ 3 ┆
└───────┴───────┘
Here, we first use the lazy
method to create a lazy DataFrame to avoid loading the data into memory. Then, we select the two columns, and use the cast
method to change the data type of col2
to int64
. Finally, we call the collect
method to execute the computation and get the result as a DataFrame.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-07-12 11:00:00 +0000
Seen: 21 times
Last updated: Mar 21 '22
Why is there a delay in reflecting a change when using the useState set method?
How to change the default keyboard shortcuts in Ace Editor?
How can the Arrow buttons be modified in the Slick slider?
When returning to HTML, does the null data in Ajax change to a different value?
How to change a Bitstring into an integer in Vertica?
How can we change a column of type String into JSON format in AWS Athena?
Is it possible to change an embedded Hibernate entity to be mandatory?
Is it possible to change the "table-layout: fixed" setting for just one row?