我希望能够连接 polars
中的数据帧其中数据框具有相同的列,但某些数据框没有列子集的数据。
更准确地说,我正在寻找 polars
相当于这个pandas
最小工作示例:
from io import StringIO
import polars as pl
import pandas as pd
TESTDATA1 = StringIO("""
col1,col2,col3
1,1,"a"
2,1,"b"
"""
)
TESTDATA2 = StringIO("""
col1,col2,col3
1,,"a"
2,,"b"
"""
)
df = pd.concat(
[
pd.read_csv(TESTDATA1),
pd.read_csv(TESTDATA2),
],
)
print(df)
这会打印
col1 col2 col3
0 1 1.0 a
1 2 1.0 b
0 1 NaN a
1 2 NaN b
我尝试了以下polars
对我不起作用的实现:
TESTDATA1 = StringIO("""
col1,col2,col3
1,1,"a"
2,1,"b"
""")
TESTDATA2 = StringIO("""
col1,col2,col3
1,,"a"
2,,"b"
""")
df = pl.concat(
[
pl.read_csv(TESTDATA1),
pl.read_csv(TESTDATA2),
],
how ="diagonal"
)
我收到错误消息:
SchemaError: cannot vstack: because column datatypes (dtypes) in the two DataFrames do not match for left.name='col2' with left.dtype=i64 != right.dtype=str with right.name='col2'
似乎空列被视为 str
在polars
并且无法与 i64
类型的其他数据框合并.
我知道这是解决我的问题的方法:
df = pl.concat(
[
pl.read_csv(TESTDATA1),
pl.read_csv(TESTDATA2).with_columns(pl.col("col2").cast(pl.Int64)),
],
how ="diagonal"
)
但实际上,我有大约二十列可能是 null
我不想把他们全部都选出来。
什么适用于 pandas
和polars
是从数据框中删除空列的情况,即
TESTDATA1 = StringIO("""
col1,col2,col3
1,1,"a"
2,1,"b"
""")
TESTDATA2 = StringIO("""
col1,col3
1,"a"
2,"b"
""")
pl.concat(
[
pl.read_csv(TESTDATA1),
pl.read_csv(TESTDATA2),
],
how ="diagonal"
)
在 pandas
,我还可以通过调用 .dropna(how="all",axis=1)
删除空列但我不知道 polars
中的等效项.
所以,总结:
- 如何连接
polars
中的数据帧如果其中一些列没有数据 (null
)? - 我怎样才能达到
.dropna(how="all",axis=1)
的效果?在polars
?
谢谢!
最佳答案
自 Polars 版本 0.19.8
起 native 支持此功能使用 diagonal_relaxed
concat 策略。
pl.concat(
[
pl.read_csv(TESTDATA1),
pl.read_csv(TESTDATA2),
],
how = "diagonal_relaxed"
)
shape: (4, 3)
┌──────┬──────┬──────┐
│ col1 ┆ col2 ┆ col3 │
│ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ str │
╞══════╪══════╪══════╡
│ 1 ┆ 1 ┆ a │
│ 2 ┆ 1 ┆ b │
│ 1 ┆ null ┆ a │
│ 2 ┆ null ┆ b │
└──────┴──────┴──────┘
关于python - 连接数据帧时处理极坐标中的空列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75693988/