gpt4 book ai didi

python - MultiIndexed DataFrame 中的前向填充日期

转载 作者:行者123 更新时间:2023-11-28 16:37:00 25 4
gpt4 key购买 nike

我有一个带有 MultiIndex 的 PANDAs DataFrame,其中一个级别代表一年:

import pandas as pd
df = pd.DataFrame(dict(A = ['foo', 'foo', 'bar', 'bar', 'bar', 'bar'],
B = ['white', 'black', 'white', 'white', 'black', 'black'],
year = [1990, 1992, 1990, 1992, 1991, 1992],
value = [3.14, 1.20, 4.56, 6.79, 0.01, 0.02]))

df = df.set_index(['A', 'B', 'year'])

我想向前填充值,但仅针对每个组中的中间年份(由 A 和 B 的交互定义)。这是输入:

                value
A B year
foo white 1990 3.14
black 1992 1.20
bar white 1990 4.56
1992 6.79
black 1991 0.01
1992 0.02

这是所需的输出,还有一行:

                value
A B year
foo white 1990 3.14
black 1992 1.20
bar white 1990 4.56
1991 4.56 <-- new forward-filled value
1992 6.79
black 1991 0.01
1992 0.02

我怎样才能简洁高效地完成这项工作?我试过使用 groupbyapply 的组合,但我是 PANDAS 的新手,一直抛出异常。

这是我如何天真地解决问题的示例:

def ffill_years(df):
df.reset_index(['A', 'B']) # drop all but 'year'
year_range = range(df['year'].min(), df['year'].max())
df.reindex(pd.Series(years)).fillna("ffill")
return df

df.groupby(level=['A', 'B']).apply(ffill_years)

当然这行不通。感谢所有提示!

最佳答案

你非常接近 - 几个小的变化:

  1. reset_index 操作不到位
  2. 无法通过名称引用索引,需要使用.index
  3. 需要在您的范围内 +1 才能包含端点
  4. reindex 也没有就位
  5. fillna 的第一个参数是填充值,使用关键字method

见下文:

def ffill_years(df):
df = df.reset_index(['A','B']) # drop all but 'year'
year_range = range(df.index.min(), df.index.max() + 1)

df = df.reindex(pd.Series(year_range)).fillna(method='ffill')
return df

结果在

In [209]: df.groupby(level=['A','B']).apply(ffill_years)
Out[209]:
A B value
A B year
bar black 1991 bar black 0.01
1992 bar black 0.02
white 1990 bar white 4.56
1991 bar white 4.56
1992 bar white 6.79
foo black 1992 foo black 1.20
white 1990 foo white 3.14

关于python - MultiIndexed DataFrame 中的前向填充日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24810665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com