Python 大熊猫的移位分组序列
我有一个分组序列,我想将其移位并添加到DF中。分组的系列看起来像:Python 大熊猫的移位分组序列,python,pandas,Python,Pandas,我有一个分组序列,我想将其移位并添加到DF中。分组的系列看起来像: month day hour_dep origin 1 1 5 LGA 1 6 EWR 4 JFK 2 LGA 4 7 EWR 4 当我移动这个序列(test_Se
month day hour_dep origin
1 1 5 LGA 1
6 EWR 4
JFK 2
LGA 4
7 EWR 4
当我移动这个序列(test_Series.shift(1))时,我得到
我想要的是:
month day hour_dep origin
1 1 5 LGA NaN
6 EWR NaN
JFK NaN
LGA 1.0
7 EWR 4.0
即,将所有观察值从前一小时转移到下一小时
谢谢你的帮助
一些代码可以轻松复制此数据结构:
np.random.seed(2)
test_df = pd.DataFrame(np.random.randint(0, 5, size=[2000,5]), columns=['Month', 'Day', 'Hour', 'Type', 'Test'])
test_series = test_df.groupby(['Month', 'Day', 'Hour', 'Type']).sum().head(10)['Test']
print(test_series)
print(test_series.shift(1)) # Observations in hour 1 do not correspond to the observations in hour 0. Observations in hour 0 should be NaN.
np.random.seed(2)
test_df = pd.DataFrame(np.random.randint(0, 5, size=[2000,5]), columns=['Month', 'Day', 'Hour', 'Type', 'Test'])
test_series = test_df.groupby(['Month', 'Day', 'Hour', 'Type']).sum().head(10)['Test']
print(test_series)
print(test_series.shift(1)) # Observations in hour 1 do not correspond to the observations in hour 0. Observations in hour 0 should be NaN.