如何通过键匹配来移动dataFrame值?例如,我有一个带有'date','id'和'num0'列的dataFrame。当我移动此dataFrame时,我想考虑'date'和'id'值。
通过此代码,我得到'当前结果'。但是我想将null值设置为row3的移位值,因为没有ID ='A'和date ='2015-10-05'的记录。
df_temp1 = pd.DataFrame({'id' : ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'],
'date' : ['2015-10-1', '2015-10-2', '2015-10-3', '2015-10-4','2015-10-1', '2015-10-2', '2015-10-3', '2015-10-4'],
'num0' : ['1', '2', '3', '4', '1', '2', '3', '4']})
df_temp1['num0_shifted'] = df_temp1['num0'].shift(-1)
df_temp1.head(10)
目前的结果:
date id num0 num0_shifted
0 2015-10-1 A 1 2
1 2015-10-2 A 2 3
2 2015-10-3 A 3 4
3 2015-10-4 A 4 1
4 2015-10-1 B 1 2
5 2015-10-2 B 2 3
6 2015-10-3 B 3 4
7 2015-10-4 B 4 NaN
我想得到的结果:
date id num0 num0_shifted
0 2015-10-1 A 1 2
1 2015-10-2 A 2 3
2 2015-10-3 A 3 4
3 2015-10-4 A 4 NaN
4 2015-10-1 B 1 2
5 2015-10-2 B 2 3
6 2015-10-3 B 3 4
7 2015-10-4 B 4 NaN
答案 0 :(得分:2)
df_temp1['num0_shifted'] = df_temp1.groupby('id')['num0'].shift(-1)
print (df_temp1)
date id num0 num0_shifted
0 2015-10-1 A 1 2
1 2015-10-2 A 2 3
2 2015-10-3 A 3 4
3 2015-10-4 A 4 NaN
4 2015-10-1 B 1 2
5 2015-10-2 B 2 3
6 2015-10-3 B 3 4
7 2015-10-4 B 4 NaN