Python 将 Pandas 数据框中的列向上移一位?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20095673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shift column in pandas dataframe up by one?
提问by natsuki_2002
I've got a pandas dataframe. I want to 'lag' one of my columns. Meaning, for example, shifting the entire column 'gdp' up by one, and then removing all the excess data at the bottom of the remaining rows so that all columns are of equal length again.
我有一个熊猫数据框。我想“滞后”我的专栏之一。意思是,例如,将整个列 'gdp' 向上移动 1,然后删除剩余行底部的所有多余数据,以便所有列的长度再次相等。
df =
y gdp cap
0 1 2 5
1 2 3 9
2 8 7 2
3 3 4 7
4 6 7 7
df_lag =
y gdp cap
0 1 3 5
1 2 7 9
2 8 4 2
3 3 7 7
Anyway to do this?
无论如何要做到这一点?
采纳答案by Wouter Overmeire
In [44]: df['gdp'] = df['gdp'].shift(-1)
In [45]: df
Out[45]:
y gdp cap
0 1 3 5
1 2 7 9
2 8 4 2
3 3 7 7
4 6 NaN 7
In [46]: df[:-1]
Out[46]:
y gdp cap
0 1 3 5
1 2 7 9
2 8 4 2
3 3 7 7
回答by PeacefulBY
shift column gdp up:
向上移动列 GDP:
df.gdp = df.gdp.shift(-1)
and then remove the last row
然后删除最后一行
回答by Bilal Mahmood
df.gdp = df.gdp.shift(-1) ## shift up
df.gdp.drop(df.gdp.shape[0] - 1,inplace = True) ## removing the last row
回答by ArmandduPlessis
To easily shift by 5 values for example and also get rid of the NaN rows, without having to keep track of the number of values you shifted by:
例如,要轻松地移动 5 个值并摆脱 NaN 行,而不必跟踪您移动的值的数量:
d['gdp'] = df['gdp'].shift(-5)
df = df.dropna()
回答by Jonas Freire
First shift the column:
首先移动列:
df['gdp'] = df['gdp'].shift(-1)
Second remove the last row which contains an NaN Cell:
其次删除包含 NaN 单元格的最后一行:
df = df[:-1]
Third reset the index:
第三次重置索引:
df = df.reset_index(drop=True)

