如何在 Pandas DataFrame 中移动几行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42732565/
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
How to shift several rows in a pandas DataFrame?
提问by ShanZhengYang
I have the following pandas Dataframe:
我有以下Pandas数据框:
import pandas as pd
data = {'one' : pd.Series([1.], index=['a']), 'two' : pd.Series([1., 2.], index=['a', 'b']), 'three' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(data)
df = df[["one", "two", "three"]]
one two three
a 1.0 1.0 1.0
b NaN 2.0 2.0
c NaN NaN 3.0
d NaN NaN 4.0
I know how to shift elements by column upwards/downwards, e.g.
我知道如何按列向上/向下移动元素,例如
df.two = df.two.shift(-1)
one two three
a 1.0 2.0 1.0
b NaN NaN 2.0
c NaN NaN 3.0
d NaN NaN 4.0
However, I would like to shift all elements in row a
over two columns and all elements in row b
over one column. The final data frame would look like this:
但是,我想将行中的所有元素a
移到两列上,并将行中的所有元素b
移到一列上。最终的数据框如下所示:
one two three
a NaN NaN 1.0
b NaN NaN 2.0
c NaN NaN 3.0
d NaN NaN 4.0
How does one do this in pandas?
如何在Pandas中做到这一点?
采纳答案by Nickil Maveli
You can transpose the initial DF
so that you have a way to access the row labels as column names inorder to perform the shift
operation.
您可以转置首字母,DF
以便您有办法将行标签作为列名称访问,以便执行shift
操作。
Shift the contents of the respective columns downward by those amounts and re-transpose it back to get the desired result.
将相应列的内容向下移动这些数量,然后将其重新调回以获得所需的结果。
df_t = df.T
df_t.assign(a=df_t['a'].shift(2), b=df_t['b'].shift(1)).T