Python 如何交换两个 DataFrame 列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25649429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:26:08  来源:igfitidea点击:

How to swap two DataFrame columns?

pythonpandas

提问by kjo

In MATLAB, to swap the first and second columns of a table A, one would do this1

在 MATLAB 中,要交换 table 的第一列和第二列A,可以这样做1

A = A(:, [2 1 3:end]);

Is there a similarly convenient way to do this if Awere a pandas DataFrameinstead?

如果A是熊猫,有没有类似的方便的方法来做到这一点DataFrame

1MATLAB uses 1-based indexing.

1MATLAB 使用基于 1 的索引。

回答by acushner

c = A.columns
A = A[c[np.r_[1, 0, 2:len(c)]]]

or, even easier:

或者,甚至更简单:

A[[c[0], c[1]]] = A[[c[1], c[0]]]

*edit: fixed per Ivan's suggestions.

*编辑:根据伊万的建议修复。

回答by EdChum

A slight variant on acushner's answer:

阿库什纳的回答略有不同:

# get a list of the columns
col_list = list(df)
# use this handy way to swap the elements
col_list[0], col_list[1] = col_list[1], col_list[0]
# assign back, the order will now be swapped
df.columns = col_list

example:

例子:

In [39]:

df = pd.DataFrame({'a':randn(3), 'b':randn(3), 'c':randn(3)})
df
Out[39]:
          a         b         c
0 -0.682446 -0.200654 -1.609470
1 -1.998113  0.806378  1.252384
2 -0.250359  3.774708  1.100771
In [40]:

col_list = list(df)
col_list[0], col_list[1] = col_list[1], col_list[0]
df.columns = col_list
df
Out[40]:
          b         a         c
0 -0.682446 -0.200654 -1.609470
1 -1.998113  0.806378  1.252384
2 -0.250359  3.774708  1.100771

UPDATE

更新

If you just want to change the column order without changing the column contents then you can reindex using fancy indexing:

如果您只想更改列顺序而不更改列内容,那么您可以使用花式索引重新索引:

In [34]:
cols = list(df)
cols[1], cols[0] = cols[0], cols[1]
cols

Out[34]:
['b', 'a', 'c']

In [35]:
df.ix[:,cols]

Out[35]:
          b         a         c
0 -0.200654 -0.682446 -1.609470
1  0.806378 -1.998113  1.252384
2  3.774708 -0.250359  1.100771

回答by kjo

I finally settled for this:

我终于解决了这个问题:

A = A.iloc[:, [1, 0] + range(2, A.shape[1])]

It's far less convenient than the MATLAB version, but I like the fact that it does not require creating temporary variables.

它远不如 MATLAB 版本方便,但我喜欢它不需要创建临时变量的事实。

回答by aspire57

pandas has reindex method that does it. You just need to give a list with the column names in the order you wish:

pandas 有 reindex 方法可以做到这一点。您只需要按照您希望的顺序列出包含列名的列表:

columns_titles = ["B","A"]
df=df.reindex(columns=columns_titles)

Cheers

干杯

回答by Luca Mastrostefano

If you have multiple columns and performance and memory are not an issue, you can simply use this function:

如果您有多个列并且性能和内存不是问题,您可以简单地使用此功能:

def swap_columns(df, c1, c2):
    df['temp'] = df[c1]
    df[c1] = df[c2]
    df[c2] = df['temp']
    df.drop(columns=['temp'], inplace=True)

回答by AturSams

I would use:

我会用:

end = df.shape[1] # or len(df.columns)
df.iloc[:, np.r_[1, 0, 2:end]

回答by Yingjian Pan

In my case, I have over 100 columns in my data frame. So instead list all columns, I wrote a short function to just switch two columns

就我而言,我的数据框中有 100 多列。所以改为列出所有列,我写了一个简短的函数来切换两列

def df_column_switch(df, column1, column2):
    i = list(df.columns)
    a, b = i.index(column1), i.index(column2)
    i[b], i[a] = i[a], i[b]
    df = df[i]
    return df

回答by nityanarayan44

For Dataframes in python, Considering that you have given the 2 columns, then:

对于python中的Dataframes,考虑到你已经给出了2列,那么:

#df is your data frame

col1='c1'
col2='c2'
df = df[[col1 if col == col2 else col2 if col == col1 else col for col in df.columns]]

回答by Srini

column swap

列交换

import pandas as pd

df = pd.read_csv('/Users/parent/Desktop/Col_swap.csv')

print(df)

columns_titles = ["A","B","C","E"]

df_reorder=df.reindex(columns=columns_titles)

df_reorder.to_csv('/Users/parent/Desktop/col_reorder1.csv', index=False)

print(df_reorder)

Output:

输出:

    B   A   C   E
0  c1  a1  b1  d1
1  c2  a2  b2  d2


    A   B   C   E
0  a1  c1  b1  d1
1  a2  c2  b2  d2