将熊猫列定位或移动到特定的列索引

时间:2019-05-08 15:44:40

标签: python pandas

我用谷歌搜索,但似乎找不到该问题的答案,或者我是用错误的方式问这个问题?

我有一个DF mydataframe,它有多列(超过75列),带有默认数字索引:

Col1 Col2 Col3 ... Coln

我需要将职位安排/更改如下:

Col1 Col3 Col2 ... Coln 

我可以使用以下方法获取Col2的索引:

mydataframe.columns.get_loc("Col2")

但我似乎无法弄清楚如何进行交换,而无需手动列出所有列,然后在列表中手动重新排列。

4 个答案:

答案 0 :(得分:1)

尝试:

new_cols = [Col1, Col3, Col2] + df.columns[3:]

df = df[new_cols]

答案 1 :(得分:1)

如何进行:

  1. 将列名存储在列表中;
  2. 交换该列表中的名称;
  3. 将新订单应用于数据框。

代码:

select *
from Companies c
join Contacts contact1 on c.first_contact=contact1.id
join Contacts contact2 on c.second_contact=contact2.id

答案 2 :(得分:0)

使用np.r_创建列索引数组:

给出以下示例:

df:
   col1  col2  col3  col4  col5  col6  col7  col8  col9  col10
0     0     1     2     3     4     5     6     7     8      9
1    10    11    12    13    14    15    16    17    18     19


i, j = df.columns.slice_locs('col2', 'col10')
df[df.columns[np.r_[:i, i+1, i, i+2:j]]]

Out[142]:
   col1  col3  col2  col4  col5  col6  col7  col8  col9  col10
0     0     2     1     3     4     5     6     7     8      9
1    10    12    11    13    14    15    16    17    18     19

答案 3 :(得分:0)

我在想你想要@sentence在假设什么。您希望交换2列的位置,而不管它们在哪里。

这是一种创造性的方法:

  1. 创建一个字典,该字典定义哪些列将用什么进行切换。
  2. 定义一个采用列名并返回顺序的函数。
  3. 使用该功能作为排序的键。

d = {'Col3': 'Col2', 'Col2': 'Col3'}
k = lambda x: df.columns.get_loc(d.get(x, x))

df[sorted(df, key=k)]

   Col0  Col1  Col3  Col2  Col4
0     0     1     3     2     4
1     5     6     8     7     9
2    10    11    13    12    14
3    15    16    18    17    19
4    20    21    23    22    24

设置

df = pd.DataFrame(
    np.arange(25).reshape(5, 5)
).add_prefix('Col')