如何交换两个DataFrame列?

kjo*_*kjo 32 python pandas

在MATLAB中,要交换表的第一列和第二列A,可以执行此操作1

A = A(:, [2 1 3:end]);
Run Code Online (Sandbox Code Playgroud)

如果A是大熊猫,有没有一种同样方便的方法DataFrame呢?

1 MATLAB使用基于1的索引.

asp*_*e57 59

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

columnsTitles=["B","A"]
df=df.reindex(columns=columnsTitles)
Run Code Online (Sandbox Code Playgroud)

干杯

  • 当您有少量列时工作。我目前有一个超过 100 列的庞大列表,标签列,我需要训练的列在中间。 (5认同)
  • 这会删除“columns_titles”中未列出的所有其他列,如果您有很多列,这会很痛苦。 (4认同)

EdC*_*ica 16

acushner的回答略有不同:

# 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
Run Code Online (Sandbox Code Playgroud)

例:

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
Run Code Online (Sandbox Code Playgroud)

UPDATE

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

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
Run Code Online (Sandbox Code Playgroud)

  • 这将交换列名,但不交换值。这不是乔问的。 (3认同)
  • 抱歉,我不关注。“示例”(更新之前)不会更改内容,仅更改标题。我缺少什么? (3认同)

acu*_*ner 8

c = A.columns
A = A[c[np.r_[1, 0, 2:len(c)]]]
Run Code Online (Sandbox Code Playgroud)

或者,甚至更简单:

A[[c[0], c[1]]] = A[[c[1], c[0]]]
Run Code Online (Sandbox Code Playgroud)

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

  • 第二个不起作用,它会以两列 1 结束 (2认同)
  • 它交换列值,但不交换标题,也可以通过任何方式交换标题 (2认同)

小智 5

就我而言,我的数据框中有 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
Run Code Online (Sandbox Code Playgroud)