如何横向堆叠Polars DataFrame的指定列?附实操实例
如何横向堆叠Polars DataFrame的列?
在Polars中,你可以通过两种简洁的方法实现横向堆叠DataFrame的列:
方法1:使用hstack()方法
hstack()是Polars专门用于横向合并列的API,可直接将目标DataFrame的列追加到当前DataFrame中:
import polars as pl df1 = pl.DataFrame( { "col1": ["a", "b", "c", "d"] } ) df2 = pl.DataFrame( { "col2": ["1", "2", "3", "4"] } ) result = df1.hstack(df2) print(result)
方法2:使用pl.concat()指定横向合并
通过pl.concat()函数,设置how="horizontal"参数,同样可以实现横向堆叠效果:
import polars as pl df1 = pl.DataFrame( { "col1": ["a", "b", "c", "d"] } ) df2 = pl.DataFrame( { "col2": ["1", "2", "3", "4"] } ) result = pl.concat([df1, df2], how="horizontal") print(result)
两种方法都会输出你预期的结果:
shape: (4, 2) ┌──────┬──────┐ │ col1 ┆ col2 │ │ --- ┆ --- │ │ str ┆ str │ ╞══════╪══════╡ │ a ┆ 1 │ │ b ┆ 2 │ │ c ┆ 3 │ │ d ┆ 4 │ └──────┴──────┘
注意:上述方法要求两个DataFrame的行数完全一致,否则会抛出匹配错误。
内容的提问来源于stack exchange,提问作者user17260574
相关产品推荐
相关产品推荐

