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

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

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 -

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

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   
└─────┴─────┴─────┘

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:

确定