【发布时间】:2017-08-01 15:14:49
【问题描述】:
我有以下熊猫数据框:
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
我知道如何按列向上/向下移动元素,例如
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 行中的所有元素移到一列上。最终的数据框如下所示:
one two three
a NaN NaN 1.0
b NaN NaN 2.0
c NaN NaN 3.0
d NaN NaN 4.0
如何在 pandas 中做到这一点?
【问题讨论】:
-
我们不需要转置DF,只需选择
shift中的axis参数即可。看我的答案!
标签: python pandas dataframe shift