将列表中的项目附加到Polars DataFrame中。

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

Append items within a list to Polars Daraframe

问题

在Polars中实现相同的操作:

  1. df2_pl = pl.DataFrame({ "a": [1, 2, 3], "b": [6, 7, 8], "c": ["a", "b", "c"]})
  2. for d in add_list:
  3. ser_pl = pl.Series(values=d, dtype=pl.Object)
  4. # 接下来怎么做?

**解决方案(为了完整性) -

  1. for d in add_list:
  2. arr = np.asarray(d).reshape(-1, len(d))
  3. df2_pl = pl.concat([df2_pl, pl.DataFrame(arr, schema=df2_pl.schema)])

这段代码会在Polars中实现与Pandas中相同的操作。

英文:

I would like to append or concatenate horizontally list of items to Polars based daraframe through for loop.

In pandas -

  1. import polars as pl
  2. import pandas as pd
  3. import numpy as np
  4. add_list = [(10, 100, 'd'), (20, 20, 'D')]
  5. df1_pd = pd.DataFrame({ "a": [1, 2, 3], "b": [6, 7, 8], "c": ["a", "b", "c"]})
  6. for d in add_list:
  7. ser_pd = pd.Series(data=d, index=df1_pd.columns)
  8. df1_pd = pd.concat([df1_pd, ser_pd.to_frame().T], ignore_index=True)

Gives desired output -

将列表中的项目附加到Polars DataFrame中。

How to achieve the same in polars?

  1. df2_pl = pl.DataFrame({ "a": [1, 2, 3], "b": [6, 7, 8], "c": ["a", "b", "c"]})
  2. for d in add_list:
  3. ser_pl = pl.Series(values=d, dtype=pl.Object)
  4. # next ??

**Solution (for the sake of completeness) -

  1. for d in add_list:
  2. arr = np.asarray(d).reshape(-1, len(d))
  3. df2_pl = pl.concat([df2_pl, pl.DataFrame(arr, schema=df2_pl.schema)])

答案1

得分: 1

我建议不要在这里使用for循环,这就是为什么pandas中的append被弃用的一种模式。

你可以这样做:

  1. In [7]: pl.concat([df2_pl, pl.DataFrame(add_list, schema=df2_pl.schema)])
  2. Out[7]:
  3. shape: (5, 3)
  4. ┌─────┬─────┬─────┐
  5. a b c
  6. --- --- ---
  7. i64 i64 str
  8. ╞═════╪═════╪═════╡
  9. 1 6 a
  10. 2 7 b
  11. 3 8 c
  12. 10 100 d
  13. 20 20 D
  14. └─────┴─────┴─────┘
英文:

I'd suggest not using a for-loop here, this is the kind of pattern why append was deprecated in pandas

You can do:

  1. In [7]: pl.concat([df2_pl, pl.DataFrame(add_list, schema=df2_pl.schema)])
  2. Out[7]:
  3. shape: (5, 3)
  4. ┌─────┬─────┬─────┐
  5. a b c
  6. --- --- ---
  7. i64 i64 str
  8. ╞═════╪═════╪═════╡
  9. 1 6 a
  10. 2 7 b
  11. 3 8 c
  12. 10 100 d
  13. 20 20 D
  14. └─────┴─────┴─────┘

huangapple
  • 本文由 发表于 2023年7月3日 20:04:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76604562.html
匿名

发表评论

匿名网友

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

确定