如何在熊猫中移动一个栏目

时间:2022-05-11 15:51:16

I would like to shift a column in a Pandas DataFrame, but I haven't been able to find a method to do it from the documentation without rewriting the whole DF. Does anyone know how to do it? DataFrame:

我想要在熊猫DataFrame中转移一列,但是在没有重写整个DF的情况下,我无法从文档中找到这样做的方法。有人知道怎么做吗?DataFrame:

##    x1   x2
##0  206  214
##1  226  234
##2  245  253
##3  265  272
##4  283  291

Desired output:

期望的输出:

##    x1   x2
##0  206  nan
##1  226  214
##2  245  234
##3  265  253
##4  283  272
##5  nan  291

3 个解决方案

#1


97  

In [18]: a
Out[18]: 
   x1  x2
0   0   5
1   1   6
2   2   7
3   3   8
4   4   9

In [19]: a.x2 = a.x2.shift(1)

In [20]: a
Out[20]: 
   x1  x2
0   0 NaN
1   1   5
2   2   6
3   3   7
4   4   8

#2


1  

If you don't want to lose the columns you shift past the end of your dataframe, simply append the required number first:

如果您不想丢失您在dataframe结束时移动的列,只需将所需的编号添加到第一个:

    offset = 5
    DF = DF.append([np.nan for x in range(offset)])
    DF = DF.shift(periods=offset)
    DF = DF.reset_index() #Only works if sequential index

#3


1  

I suppose imports

我想进口

import pandas as pd
import numpy as np

First append new row with NaN, NaN,... at the end of DataFrame (df).

第一次与NaN, NaN,…在DataFrame (df)的末尾。

s1 = df.iloc[0]    # copy 1st row to a new Series s1
s1[:] = np.NaN     # set all values to NaN
df2 = df.append(s1, ignore_index=True)  # add s1 to the end of df

It will create new DF df2. Maybe there is more elegant way but this works.

它将创建新的DF df2。也许有更优雅的方式,但这是可行的。

Now you can shift it:

现在你可以改变它:

df2.x2 = df2.x2.shift(1)  # shift what you want

#1


97  

In [18]: a
Out[18]: 
   x1  x2
0   0   5
1   1   6
2   2   7
3   3   8
4   4   9

In [19]: a.x2 = a.x2.shift(1)

In [20]: a
Out[20]: 
   x1  x2
0   0 NaN
1   1   5
2   2   6
3   3   7
4   4   8

#2


1  

If you don't want to lose the columns you shift past the end of your dataframe, simply append the required number first:

如果您不想丢失您在dataframe结束时移动的列,只需将所需的编号添加到第一个:

    offset = 5
    DF = DF.append([np.nan for x in range(offset)])
    DF = DF.shift(periods=offset)
    DF = DF.reset_index() #Only works if sequential index

#3


1  

I suppose imports

我想进口

import pandas as pd
import numpy as np

First append new row with NaN, NaN,... at the end of DataFrame (df).

第一次与NaN, NaN,…在DataFrame (df)的末尾。

s1 = df.iloc[0]    # copy 1st row to a new Series s1
s1[:] = np.NaN     # set all values to NaN
df2 = df.append(s1, ignore_index=True)  # add s1 to the end of df

It will create new DF df2. Maybe there is more elegant way but this works.

它将创建新的DF df2。也许有更优雅的方式,但这是可行的。

Now you can shift it:

现在你可以改变它:

df2.x2 = df2.x2.shift(1)  # shift what you want