Python Polars 如何处理索引?

How is Python Polars treating the index?

我想在 Python 中尝试 polars 所以我想做的是连接从 jsons 读取的几个数据帧。当我将索引更改为 date 并查看 lala1.head() 时,我发现列 date 已经消失,所以我基本上丢失了索引。是否有更好的解决方案,或者我需要按日期排序,这基本上与将索引设置为 date?

相同
import polars as pl

quarterly_balance_df = pl.read_json('../AAPL/single_statements/1985-09-30-quarterly_balance.json')


q1 = quarterly_balance_df.lazy().with_column(pl.col("date").str.strptime(pl.Date, "%Y-%m-%d"))
quarterly_balance_df = q1.collect()
q2 = quarterly_balance_df.lazy().with_column(pl.col("fillingDate").str.strptime(pl.Date, "%Y-%m-%d"))
quarterly_balance_df = q2.collect()
q3 = quarterly_balance_df.lazy().with_column(pl.col("acceptedDate").str.strptime(pl.Date, "%Y-%m-%d"))
quarterly_balance_df = q3.collect()

quarterly_balance_df2 = pl.read_json('../AAPL/single_statements/1986-09-30-quarterly_balance.json')

q1 = quarterly_balance_df2.lazy().with_column(pl.col("date").str.strptime(pl.Date, "%Y-%m-%d"))
quarterly_balance_df2 = q1.collect()
q2 = quarterly_balance_df2.lazy().with_column(pl.col("fillingDate").str.strptime(pl.Date, "%Y-%m-%d"))
quarterly_balance_df2 = q2.collect()
q3 = quarterly_balance_df2.lazy().with_column(pl.col("acceptedDate").str.strptime(pl.Date, "%Y-%m-%d"))
quarterly_balance_df2 = q3.collect()

lala1 = pl.from_pandas(quarterly_balance_df.to_pandas().set_index('date'))
lala2 = pl.from_pandas(quarterly_balance_df.to_pandas().set_index('date'))

test = pl.concat([lala1,lala2])

Polars 有意消除了索引的概念。事实上,Polars "Cookbook" 甚至对索引进行了说明:

They are not needed. Not having them makes things easier. Convince me otherwise

确实,from_pandas 方法会忽略任何索引。例如,如果我们从以下数据开始:

import polars as pl

df = pl.DataFrame(
    {
        "key": [1, 2],
        "var1": ["a", "b"],
        "var2": ["r", "s"],
    }
)
print(df)
shape: (2, 3)
┌─────┬──────┬──────┐
│ key ┆ var1 ┆ var2 │
│ --- ┆ ---  ┆ ---  │
│ i64 ┆ str  ┆ str  │
╞═════╪══════╪══════╡
│ 1   ┆ a    ┆ r    │
├╌╌╌╌╌┼╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ 2   ┆ b    ┆ s    │
└─────┴──────┴──────┘

现在,如果我们将这个 Polars 数据集导出到 Panda,将 key 设置为 Pandas 中的索引,然后 re-import 到 Polars,您将看到 'key' 列消失。

pl.from_pandas(df.to_pandas().set_index("key"))
shape: (2, 2)
┌──────┬──────┐
│ var1 ┆ var2 │
│ ---  ┆ ---  │
│ str  ┆ str  │
╞══════╪══════╡
│ a    ┆ r    │
├╌╌╌╌╌╌┼╌╌╌╌╌╌┤
│ b    ┆ s    │
└──────┴──────┘

这就是您的 Date 列消失的原因。

在 Polars 中,您可以按 DataFrame 中的任意一组列进行排序、汇总或连接。无需声明索引。

我建议通过 Polars 查看 Cookbook。这是一个很好的起点。还有一个部分供来自 Pandas.

的人使用