gpt4 book ai didi

python - Pandas : groupby ffill for multiple columns

转载 作者:太空宇宙 更新时间:2023-11-04 09:31:26 24 4
gpt4 key购买 nike

我有以下带有一些缺失值的 DataFrame。我想使用 ffill() 来填充 var1var2 中的缺失值,按 date 分组>建筑。我一次可以对一个变量执行此操作,但是当我尝试对两个变量执行此操作时,它会崩溃。如何同时对两个变量执行此操作,同时不修改但保留 var3var4

df = pd.DataFrame({
'date': ['2019-01-01','2019-01-01','2019-01-01','2019-01-01','2019-02-01','2019-02-01','2019-02-01','2019-02-01'],
'building': ['a', 'a', 'b', 'b', 'a', 'a', 'b', 'b'],
'var1': [1.5, np.nan, 2.1, 2.2, 1.2, 1.3, 2.4, np.nan],
'var2': [100, 110, 105, np.nan, 102, np.nan, 103, 107],
'var3': [10, 11, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
'var4': [1, 2, 3, 4, 5, 6, 7, 8]
})
df
date building var1 var2 var3 var4
0 2019-01-01 a 1.5 100.0 10.0 1
1 2019-01-01 a NaN 110.0 11.0 2
2 2019-01-01 b 2.1 105.0 NaN 3
3 2019-01-01 b 2.2 NaN NaN 4
4 2019-02-01 a 1.2 102.0 NaN 5
5 2019-02-01 a 1.3 NaN NaN 6
6 2019-02-01 b 2.4 103.0 NaN 7
7 2019-02-01 b NaN 107.0 NaN 8

# This works
df['var1'] = df.groupby(['date', 'building'])['var1'].ffill()
df['var2'] = df.groupby(['date', 'building'])['var2'].ffill()
df
date building var1 var2 var3 var4
0 2019-01-01 a 1.5 100.0 10.0 1
1 2019-01-01 a 1.5 110.0 11.0 2
2 2019-01-01 b 2.1 105.0 NaN 3
3 2019-01-01 b 2.2 105.0 NaN 4
4 2019-02-01 a 1.2 102.0 NaN 5
5 2019-02-01 a 1.3 102.0 NaN 6
6 2019-02-01 b 2.4 103.0 NaN 7
7 2019-02-01 b 2.4 107.0 NaN 8

# This doesn't work
df[['var1', 'var2']] = df.groupby(['date', 'building'])[['var1', 'var2']].ffill()
ValueError: Columns must be same length as key

最佳答案

我认为您需要在 groupby 之前添加 fillna

df[["var1", "var2"]] = df[["var1", "var2"]].fillna(df.groupby(['date', 'building'])[["var1", "var2"]].ffill())

date building var1 var2 var3 var4
0 2019-01-01 a 1.5 100.0 10.0 1
1 2019-01-01 a 1.5 110.0 11.0 2
2 2019-01-01 b 2.1 105.0 NaN 3
3 2019-01-01 b 2.2 105.0 NaN 4
4 2019-02-01 a 1.2 102.0 NaN 5
5 2019-02-01 a 1.3 102.0 NaN 6
6 2019-02-01 b 2.4 103.0 NaN 7
7 2019-02-01 b 2.4 107.0 NaN 8

关于 python - Pandas : groupby ffill for multiple columns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55596674/

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