How to convert polars dataframe column type from float64 to int64?

huangapple go评论62阅读模式
英文:

How to convert polars dataframe column type from float64 to int64?

问题

以下是您要翻译的内容:

我有一个polars数据框,如下:

import polars as pl
df = pl.DataFrame({"foo": [1.0, 2.0, 3.0], "bar": [11, 5, 8]})

如何将第一列转换为int64类型?

我尝试了一些方法,例如:

df.select(pl.col('foo')) = df.select(pl.col('foo')).cast(pl.Int64)

但它不起作用。

在Pandas中,这非常简单:

df['foo'] = df['foo'].astype('int64')

谢谢。

英文:

I have a polars dataframe, like:

import polars as pl
df = pl.DataFrame({"foo": [1.0, 2.0, 3.0], "bar": [11, 5, 8]})

How do I convert the first column to int64 type?<br>
I was trying something like:

df.select(pl.col(&#39;foo&#39;)) = df.select(pl.col(&#39;foo&#39;)).cast(pl.Int64)

but it is not working.<br>
In Pandas it was super easy:

df[&#39;foo&#39;] = df[&#39;foo&#39;].astype(&#39;int64&#39;)

Thanks.

答案1

得分: 4

将您的col选择出来,将其转换为(int64),然后添加回原始的DataFrame with_columns

df = df.with_columns(pl.col("foo").cast(pl.Int64))

输出:

print(df)

shape: (3, 2)
┌─────┬─────┐
│ foo ┆ bar │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1   ┆ 11  │
│ 2   ┆ 5   │
│ 3   ┆ 8   │
└─────┴─────┘
英文:

Select your col, cast it to (int64) and add it back to the original DataFrame with_columns.

df = df.with_columns(pl.col(&quot;foo&quot;).cast(pl.Int64))

Output :

print(df)

shape: (3, 2)
┌─────┬─────┐
│ foo ┆ bar │
│ --- ┆ --- │
│ i64 ┆ i64 │
╞═════╪═════╡
│ 1   ┆ 11  │
│ 2   ┆ 5   │
│ 3   ┆ 8   │
└─────┴─────┘

huangapple
  • 本文由 发表于 2023年4月13日 19:29:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76004898.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定