gpt4 book ai didi

python - Pandas |分组数据框中的 Fillna(ffill) 未填充

转载 作者:行者123 更新时间:2023-12-01 03:31:03 24 4
gpt4 key购买 nike

我有一个 MultIndex 数据帧,并尝试填充一个值 MAX_PTS_YR,以便 t+1 年的 MAX_PTS_YR > 等于 t 中的 MAX_PTS_YR

因此:2016 中的 MAX_PTS_YR 应等于 116

使用 nth,我找到了前一年的 MAX_PTS:

DF['MAX_PTS_YR'] = DF.groupby(by=['Affiliation','Year'],as_index=False)['PtsYr'].nth(-1)


Affiliation mkid Year PtsYr MAX_PTS_YR
MVPAFL0003 10176228 2015 96.0 NaN
MVPAFL0003 10176228 2015 96.0 NaN
MVPAFL0003 10176228 2015 106.0 NaN
MVPAFL0003 10176228 2015 116.0 116.0
MVPAFL0003 10176228 2016 10.0 NaN
MVPAFL0003 10176228 2016 10.0 NaN
MVPAFL0003 10176228 2016 20.0 NaN
MVPAFL0003 10176228 2016 20.0 NaN
MVPAFL0003 10176228 2016 30.0 NaN
MVPAFL0003 10176228 2016 40.0 NaN
MVPAFL0003 10176228 2016 50.0 NaN
MVPAFL0003 10176228 2016 50.0 NaN
MVPAFL0003 10176228 2016 52.0 NaN
MVPAFL0003 10176228 2016 62.0 NaN
MVPAFL0003 10176228 2016 62.0 NaN
MVPAFL0003 10176228 2016 82.0 NaN
MVPAFL0003 10176228 2016 94.0 NaN
MVPAFL0003 10176228 2016 94.0 NaN
MVPAFL0003 10176228 2016 94.0 NaN
MVPAFL0003 10176228 2016 104.0 NaN
MVPAFL0003 10176228 2016 114.0 114.0

我想我可以fillna加入那个隶属组:

DF.groupby(by=['Affiliation'],as_index=False)['MAX_PTS_AFFIL'].fillna(method='ffill',inplace=True)

但是当我这样做时,没有填充 NaN 值。

有什么想法吗?

最佳答案

# get just the series you are filling to simplify things
s1 = df.set_index(['Affiliation', 'Year']).MAX_PTS_YR

# groupby to get the max per group
mx = s1.groupby(level=[0, 1]).max()

# shift your year index by one year
mx.index.set_levels(mx.index.levels[1] + 1, 1, inplace=True)

# fill in missing bits
s1.fillna(mx)
<小时/>
Affiliation  Year
MVPAFL0003 2015 NaN
2015 NaN
2015 NaN
2015 116.0
2016 116.0
2016 116.0
2016 116.0
2016 116.0
2016 116.0
2016 116.0
2016 116.0
2016 116.0
2016 116.0
2016 116.0
2016 116.0
2016 116.0
2016 116.0
2016 116.0
2016 116.0
2016 116.0
2016 114.0
Name: MAX_PTS_YR, dtype: float64
<小时/>

现在分配给 df

df.MAX_PTS_YR = (s1.fillna(mx).values)
df

enter image description here

关于python - Pandas |分组数据框中的 Fillna(ffill) 未填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40939461/

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