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

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

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

问题

以下是您要翻译的内容:

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

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

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

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

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

但它不起作用。

在Pandas中,这非常简单:

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

谢谢。

英文:

I have a polars dataframe, like:

  1. import polars as pl
  2. 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:

  1. 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:

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

Thanks.

答案1

得分: 4

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

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

输出:

  1. print(df)
  2. shape: (3, 2)
  3. ┌─────┬─────┐
  4. foo bar
  5. --- ---
  6. i64 i64
  7. ╞═════╪═════╡
  8. 1 11
  9. 2 5
  10. 3 8
  11. └─────┴─────┘
英文:

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

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

Output :

  1. print(df)
  2. shape: (3, 2)
  3. ┌─────┬─────┐
  4. foo bar
  5. --- ---
  6. i64 i64
  7. ╞═════╪═════╡
  8. 1 11
  9. 2 5
  10. 3 8
  11. └─────┴─────┘

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:

确定