英文:
Append items within a list to Polars Daraframe
问题
在Polars中实现相同的操作:
df2_pl = pl.DataFrame({ "a": [1, 2, 3], "b": [6, 7, 8], "c": ["a", "b", "c"]})
for d in add_list:
ser_pl = pl.Series(values=d, dtype=pl.Object)
# 接下来怎么做?
**解决方案(为了完整性) -
for d in add_list:
arr = np.asarray(d).reshape(-1, len(d))
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 -
import polars as pl
import pandas as pd
import numpy as np
add_list = [(10, 100, 'd'), (20, 20, 'D')]
df1_pd = pd.DataFrame({ "a": [1, 2, 3], "b": [6, 7, 8], "c": ["a", "b", "c"]})
for d in add_list:
ser_pd = pd.Series(data=d, index=df1_pd.columns)
df1_pd = pd.concat([df1_pd, ser_pd.to_frame().T], ignore_index=True)
Gives desired output -
How to achieve the same in polars?
df2_pl = pl.DataFrame({ "a": [1, 2, 3], "b": [6, 7, 8], "c": ["a", "b", "c"]})
for d in add_list:
ser_pl = pl.Series(values=d, dtype=pl.Object)
# next ??
**Solution (for the sake of completeness) -
for d in add_list:
arr = np.asarray(d).reshape(-1, len(d))
df2_pl = pl.concat([df2_pl, pl.DataFrame(arr, schema=df2_pl.schema)])
答案1
得分: 1
我建议不要在这里使用for循环,这就是为什么pandas
中的append
被弃用的一种模式。
你可以这样做:
In [7]: pl.concat([df2_pl, pl.DataFrame(add_list, schema=df2_pl.schema)])
Out[7]:
shape: (5, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ 6 ┆ a │
│ 2 ┆ 7 ┆ b │
│ 3 ┆ 8 ┆ c │
│ 10 ┆ 100 ┆ d │
│ 20 ┆ 20 ┆ D │
└─────┴─────┴─────┘
英文:
I'd suggest not using a for-loop here, this is the kind of pattern why append
was deprecated in pandas
You can do:
In [7]: pl.concat([df2_pl, pl.DataFrame(add_list, schema=df2_pl.schema)])
Out[7]:
shape: (5, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ str │
╞═════╪═════╪═════╡
│ 1 ┆ 6 ┆ a │
│ 2 ┆ 7 ┆ b │
│ 3 ┆ 8 ┆ c │
│ 10 ┆ 100 ┆ d │
│ 20 ┆ 20 ┆ D │
└─────┴─────┴─────┘
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论