如何在 pandas DataFrame中移动几行? [英] How to shift several rows in a pandas DataFrame?
本文介绍了如何在 pandas DataFrame中移动几行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下熊猫数据框:
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
但是,我想将行a
中的所有元素移到两列上,并将行b
中的所有元素移到一列上.最终的数据帧如下所示:
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:
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?
推荐答案
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.
将各列的内容向下移动这些量,然后将其重新移回以获得所需的结果.
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
这篇关于如何在 pandas DataFrame中移动几行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文