简体   繁体   English

如何在 pandas 数据帧的特定列索引处插入列? (更改 pandas 数据帧中的列顺序)

[英]how do I insert a column at a specific column index in pandas data frame? (Change column order in pandas data frame)

I have a pandas data frame and I want to move the "F" column to after the "B" column.我有一个 pandas 数据框,我想将“F”列移到“B”列之后。 Is there a way to do that?有没有办法做到这一点?

   A  B  C    D  E  F
0  7  1       8  1  6
1  8  2  5    8  5  8
2  9  3  6    8     5
3  1     8    1  3  4
4  6  8  2    5  0  9
5     2  N/A  1  3  8


df2
   A  B  F  C    D  E  
0  7  1  6       8  1  
1  8  2  8  5    8  5  
2  9  3  5  6    8     
3  1     4  8    1  3  
4  6  8  9  2    5  0  
5     2  8  N/A  1  3  

So it should finally look like df2.所以它最终应该看起来像 df2。 Thanks in advance.提前致谢。

You can try df.insert + df.pop after getting location of B by get_loc您可以在通过get_loc获取 B 的位置后尝试df.insert + df.pop

df.insert(df.columns.get_loc("B")+1,"F",df.pop("F"))
print(df)

     A  B    F    C  D    E
0  7.0  1  6.0  NaN  8  1.0
1  8.0  2  8.0  5.0  8  5.0
2  9.0  3  5.0  6.0  8  NaN
3  1.0  8  NaN  1.0  3  4.0
4  6.0  8  9.0  2.0  5  0.0
5  NaN  2  8.0  NaN  1  3.0

Another minimalist, (and very specific:) approach:另一种极简主义(而且非常具体:)方法:

df = df[list('ABFCDE')]
Here is a very simple answer to this(only one line).这是一个非常简单的答案(只有一行)。 Giving littlebit more explanation to the answer from @warped对@warped的答案给出更多解释

You can do that after you added the 'n' column into your df as follows.您可以在将“n”列添加到 df 后执行此操作,如下所示。

import pandas as pd
df = pd.DataFrame({'l':['a','b','c','d'], 'v':[1,2,1,2]})
df['n'] = 0

df
    l   v   n
0   a   1   0
1   b   2   0
2   c   1   0
3   d   2   0

# here you can add the below code and it should work.
df = df[list('nlv')]
df

    n   l   v
0   0   a   1
1   0   b   2
2   0   c   1
3   0   d   2



However, if you have words in your columns names instead of letters. It should include two brackets around your column names. 

import pandas as pd
df = pd.DataFrame({'Upper':['a','b','c','d'], 'Lower':[1,2,1,2]})
df['Net'] = 0
df['Mid'] = 2
df['Zsore'] = 2

df

    Upper   Lower   Net Mid Zsore
0   a       1       0   2   2
1   b       2       0   2   2
2   c       1       0   2   2
3   d       2       0   2   2

# here you can add below line and it should work 
df = df[list(('Mid','Upper', 'Lower', 'Net','Zsore'))]
df

   Mid  Upper   Lower   Net Zsore
0   2   a       1       0   2
1   2   b       2       0   2
2   2   c       1       0   2
3   2   d       2       0   2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM