如何在极坐标中执行 pandas 重新索引

问题描述 投票:0回答:1

在 pandas 中,我可以使用多索引

reindex()
数据框以使每个组的日期范围保持一致。有什么方法可以在极坐标中产生相同的结果吗?

请参阅下面使用 pandas 的示例:

import pandas as pd
data = pd.DataFrame({
             "date":pd.date_range("2022-01-01", "2022-06-01", freq="MS"),
             "group":["A", "A", "A", "B", "B", "B"],
             "value":[10,20,30,40,50,60]
     }).set_index(["group", "date"])
new_index = pd.MultiIndex.from_product([data.index.levels[0].tolist(), data.index.levels[1].tolist()], names=["group", "date"])
data.reindex(new_index)

将数据转换为:

                  value
group date             
A     2022-01-01     10
      2022-02-01     20
      2022-03-01     30
B     2022-04-01     40
      2022-05-01     50
      2022-06-01     60

下面两个组具有相同的日期范围:

                  value
group date             
A     2022-01-01   10.0
      2022-02-01   20.0
      2022-03-01   30.0
      2022-04-01    NaN
      2022-05-01    NaN
      2022-06-01    NaN
B     2022-01-01    NaN
      2022-02-01    NaN
      2022-03-01    NaN
      2022-04-01   40.0
      2022-05-01   50.0
      2022-06-01   60.0
python-polars
1个回答
3
投票

正如您可能已经读到的,极性不使用索引

在这种情况下,您的

new_index
是索引列的唯一值的交叉联接,可以轻松地在极坐标中重现。

pldata=pl.DataFrame({
            "date":pl.date_range(datetime(2022,1,1), datetime(2022,6,1),'1mo',eager=True),
            "group":["A", "A", "A", "B", "B", "B"],
            "value":[10,20,30,40,50,60]
    })

pl_index = pldata.select(pl.col('date').unique()) \
        .join(
              pldata.select(pl.col('group').unique()), 
         how='cross'
         )

然后,您可以执行另一个连接,而不是重新索引命令,这次是对这些列进行外部连接,并进行排序以获取订单

pldata.join(plnew_index, on=['date','group'], how='full', coalesce=True).sort('group','date')

您可以创建一个辅助函数来为任意数量的索引列创建

plnew_index

def make_plindex(df, indexcols):
    newdf=df.select(pl.col(indexcols[0]).unique())
    for curcol in indexcols[1:]:
        newdf=newdf.join(df.select(pl.col(curcol).unique()), how='cross')
    return newdf

当然,如果您实际上并不关心中间 df,您可以通过将外部联接放入其中返回最终结果来扩展该函数

def make_nullrows(df, indexcols):
    newdf=df.select(pl.col(indexcols[0]).unique())
    for curcol in indexcols[1:]:
        newdf=newdf.join(df.select(pl.col(curcol).unique()), how='cross')
    return df.join(newdf, on=indexcols, how='full', coalesce=True)

那么你就可以做

make_nullrows(pldata, ['group','date'])
© www.soinside.com 2019 - 2024. All rights reserved.