[英]Filling previous values within a group in Pandas
我希望“ID”组中S0.0,S1.0,S2.0
中的值ffill()
ID Close S0.0 S1.0 S2.0
0 UNITY 11.66 NaN 54 NaN
1 UNITY 11.55 56 NaN NaN
2 UNITY 11.59 NaN NaN 78
3 TRINITY 11.69 47 NaN NaN
4 TRINITY 11.37 NaN 69 NaN
5 TRINITY 11.89 NaN NaN 70
预期结果:
ID Close S0.0 S1.0 S2.0
0 UNITY 11.66 NaN 54 NaN
1 UNITY 11.55 56 54 NaN
2 UNITY 11.59 56 54 78
3 TRINITY 11.69 47 NaN NaN
4 TRINITY 11.37 47 69 NaN
5 TRINITY 11.89 47 69 70
以下是我的尝试及其不良结果:
尝试 1:
df[df['S0.0']==""] = np.NaN
df[df['S1.0']==""] = np.NaN
df[df['S2.0']==""] = np.NaN
df['S0.0'].groupby('ID').fillna(method='ffill', inplace = True)
df['S1.0'].groupby('ID').fillna(method='ffill', inplace = True)
df['S2.0'].groupby('ID').fillna(method='ffill', inplace = True)
output:
raise KeyError(gpr)
KeyError: 'ID'
尝试 2:
df.groupby('ID')[['S0.0', 'S1.0', 'S2.0']].ffill()
#this makes no difference to the data.
#but when I try this:
df = df.groupby('ID')[['S0.0', 'S1.0', 'S2.0']].ffill()
df
Output:
S0.0 S1.0 S2.0
NaN 54 NaN
56 54 NaN
56 54 78
47 NaN NaN
47 69 NaN
47 69 70
这又不是我想要的。 小帮助将不胜感激。 谢谢!
做就是了:
df[['S0.0', 'S1.0', 'S2.0']] = df.groupby('ID')[['S0.0', 'S1.0', 'S2.0']].ffill()
print(df)
Output
Close S0.0 S1.0 S2.0
0 11.66 NaN 54.0 NaN
1 11.55 56.0 54.0 NaN
2 11.59 56.0 54.0 78.0
3 11.69 47.0 NaN NaN
4 11.37 47.0 69.0 NaN
5 11.89 47.0 69.0 70.0
更新第二次尝试是正确的。 只是不要指定 Sx.0 的列。
id = df.ID
df = pd.concat([id,df.groupby('ID').ffill()],axis=1)
output:
ID Close S0.0 S1.0 S2.0
0 UNITY 11.66 NaN 54.0 NaN
1 UNITY 11.55 56.0 54.0 NaN
2 UNITY 11.59 56.0 54.0 78.0
3 TRINITY 11.69 47.0 NaN NaN
4 TRINITY 11.37 47.0 69.0 NaN
5 TRINITY 11.89 47.0 69.0 70.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.