python - 连接数据帧时处理极坐标中的空列

标签 python python-3.x pandas python-polars

我希望能够连接 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'

似乎空列被视为 strpolars并且无法与 i64 类型的其他数据框合并.

我知道这是解决我的问题的方法:

df = pl.concat(
    [
        pl.read_csv(TESTDATA1),
        pl.read_csv(TESTDATA2).with_columns(pl.col("col2").cast(pl.Int64)),
    ],
    how ="diagonal"
)

但实际上,我有大约二十列可能是 null我不想把他们全部都选出来。

什么适用于 pandaspolars是从数据框中删除空列的情况,即


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/

相关文章:

python - 在 python 中转义 MySQL 的引号

python - 简单的原始输入和条件

python - Python 3 的枚举速度是否比 Python 2 慢?

python - 如何在 Python 中将 typing.Union 转换为其子类型之一?

python - Pandas get_level_values 表现出乎意料

python - 更新未屏蔽的 numpy 数组

python - 如何从 PyListObject 获取 `pop` 元素?

python - 猎鹰,属性错误 : 'API' object has no attribute 'create'

Python - data.to_csv 输出格式

python - groupby 的标准方法(例如平均值、总和、第一)的按列异常可能吗?