Python 2.7:按天和列值移动数据框 [英] Python 2.7: shift a dataframe by day and a column value
问题描述
我有一个名为 df1 的数据框,如下所示:
I have a dataframe named df1 as following:
df1:
a b id
2010-01-01 2 3 21
2010-01-01 2 4 22
2010-01-01 3 5 23
2010-01-01 4 6 24
2010-01-02 1 4 21
2010-01-02 2 5 22
2010-01-02 3 6 23
2010-01-02 4 7 24
2010-01-03 1 8 21
2010-01-03 2 9 22
2010-01-03 3 10 23
2010-01-03 4 11 24
...........................
我想移动a、b和id的值,第i行的值变成第i+1行的值.可以看到df1,同一个日期有几行,id不一样.我想移动df1,我的意思是2010-01-02的值是基于id的2010-01-03值(我的意思是id 21的2010-01-02值,是2010-01-03 id 21 的值).谢谢!
I want to shift the value of a, b and id, the i rows value become the i+1 rows value. As you can see the df1, the same date have several rows, and the id is different. I want to shift the df1, I mean the 2010-01-02 value to be the 2010-01-03 value based on the id(I mean that 2010-01-02 value of id 21, to be the 2010-01-03 value of id 21). Thanks!
我想要的答案:
a b id
2010-01-01 Nan Nan Nan
2010-01-01 Nan Nan Nan
2010-01-01 Nan Nan Nan
2010-01-01 Nan Nan Nan
2010-01-02 2 3 21
2010-01-02 2 4 22
2010-01-02 3 5 23
2010-01-02 4 6 24
2010-01-03 1 4 21
2010-01-03 2 5 22
2010-01-03 3 6 23
2010-01-03 4 7 24
...........................
推荐答案
如果所有组的长度相同(在示例 4 中)并且 DatetimeIndex
已排序:
If all groups are same length (in sample 4) and DatetimeIndex
is sorted:
df2 = df.shift((df.index == df.index[0]).sum())
print (df2)
a b id
2010-01-01 NaN NaN NaN
2010-01-01 NaN NaN NaN
2010-01-01 NaN NaN NaN
2010-01-01 NaN NaN NaN
2010-01-02 2.0 3.0 21.0
2010-01-02 2.0 4.0 22.0
2010-01-02 3.0 5.0 23.0
2010-01-02 4.0 6.0 24.0
2010-01-03 1.0 4.0 21.0
2010-01-03 2.0 5.0 22.0
2010-01-03 3.0 6.0 23.0
2010-01-03 4.0 7.0 24.0
但是如果需要将索引值移动一天:
But if need shift values of index by one day:
df3 = df.shift(1, freq='D')
print (df3)
a b id
2010-01-02 2 3 21
2010-01-02 2 4 22
2010-01-02 3 5 23
2010-01-02 4 6 24
2010-01-03 1 4 21
2010-01-03 2 5 22
2010-01-03 3 6 23
2010-01-03 4 7 24
2010-01-04 1 8 21
2010-01-04 2 9 22
2010-01-04 3 10 23
2010-01-04 4 11 24
这篇关于Python 2.7:按天和列值移动数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!