Pandas:将一组值向下移动一行 [英] Pandas: Shift down values by one row within a group
问题描述
我有一个 Pandas 数据框,我想创建一个新列,其值是另一列的值,向下移动一行.最后一行应显示 NaN.
问题是我想按组执行此操作,每组的最后一行显示 NaN.不要让组的最后一行从恰好在数据帧中相邻的组中窃取"一个值.
我尝试的实现很可耻地被破坏了,所以我显然误解了一些基本的东西.
df['B_shifted'] = df.groupby(['A'])['B'].transform(lambda x:x.values[1:])
Shift 作用于 groupby 子句的输出:
<预><代码>>>>df = pandas.DataFrame(numpy.random.randint(1,3, (10,5)), columns=['a','b','c','d','e'])>>>dfa b c d0 2 1 2 1 11 2 1 1 1 12 1 2 2 1 23 1 2 1 1 24 2 2 1 1 25 2 2 2 2 16 2 2 1 1 17 2 2 2 1 18 2 2 2 2 19 2 2 2 2 1对于 df.groupby('a') 中的 k, v:打印 k打印正常"打印 v打印移位"打印 v.shift(1)1普通的a b c d2 1 2 2 1 23 1 2 1 1 2移位a b c d2 南南南南南南南3 1 2 2 1 22普通的a b c d0 2 1 2 1 11 2 1 1 1 14 2 2 1 1 25 2 2 2 2 16 2 2 1 1 17 2 2 2 1 18 2 2 2 2 19 2 2 2 2 1移位a b c d0 南南南南南南南1 2 1 2 1 14 2 1 1 1 15 2 2 1 1 26 2 2 2 2 17 2 2 1 1 18 2 2 2 1 19 2 2 2 2 1I have a Pandas dataframe, and I want to create a new column whose values are that of another column, shifted down by one row. The last row should show NaN.
The catch is that I want to do this by group, with the last row of each group showing NaN. NOT have the last row of a group "steal" a value from a group that happens to be adjacent in the dataframe.
My attempted implementation is quite shamefully broken, so I'm clearly misunderstanding something fundamental.
df['B_shifted'] = df.groupby(['A'])['B'].transform(lambda x:x.values[1:])
Shift works on the output of the groupby clause:
>>> df = pandas.DataFrame(numpy.random.randint(1,3, (10,5)), columns=['a','b','c','d','e'])
>>> df
a b c d e
0 2 1 2 1 1
1 2 1 1 1 1
2 1 2 2 1 2
3 1 2 1 1 2
4 2 2 1 1 2
5 2 2 2 2 1
6 2 2 1 1 1
7 2 2 2 1 1
8 2 2 2 2 1
9 2 2 2 2 1
for k, v in df.groupby('a'):
print k
print 'normal'
print v
print 'shifted'
print v.shift(1)
1
normal
a b c d e
2 1 2 2 1 2
3 1 2 1 1 2
shifted
a b c d e
2 NaN NaN NaN NaN NaN
3 1 2 2 1 2
2
normal
a b c d e
0 2 1 2 1 1
1 2 1 1 1 1
4 2 2 1 1 2
5 2 2 2 2 1
6 2 2 1 1 1
7 2 2 2 1 1
8 2 2 2 2 1
9 2 2 2 2 1
shifted
a b c d e
0 NaN NaN NaN NaN NaN
1 2 1 2 1 1
4 2 1 1 1 1
5 2 2 1 1 2
6 2 2 2 2 1
7 2 2 1 1 1
8 2 2 2 1 1
9 2 2 2 2 1
这篇关于Pandas:将一组值向下移动一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!