matlab 交换两个数组,如何交换两个数据帧列?

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值