Sha*_*ang 8 python shift dataframe pandas
我有以下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
Run Code Online (Sandbox Code Playgroud)
我知道如何按列向上/向下移动元素,例如
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
Run Code Online (Sandbox Code Playgroud)
但是,我想将行中的所有元素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
Run Code Online (Sandbox Code Playgroud)
大熊猫如何做到这一点?
您可以对首字母进行转置,DF以便您可以将行标签作为列名进行访问,以执行该shift操作。
将各列的内容向下移动这些量,然后重新移回以获得所需的结果。
df_t = df.T
df_t.assign(a=df_t['a'].shift(2), b=df_t['b'].shift(1)).T
Run Code Online (Sandbox Code Playgroud)