【问题标题】:how to sort only some of the columns in a data frame in pandas?如何仅对熊猫数据框中的某些列进行排序?
【发布时间】:2013-09-05 22:55:50
【问题描述】:

有没有办法以用户定义的方式仅对列表的某些元素进行排序?

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.rand(5, 6), columns=['x','a','c','y','b','z'])

我想以前 3 列为 [x, y, z] 的方式对 df 的列进行排序(按此顺序),其余列的放置位置无关紧要。

对于这个例子,我可以手动完成,但随着列表变大,使用更合适的方法会很方便。

我曾想过使用l = df_r.columns.tolist(),但即使只有一个列表,我也无法弄清楚如何使用它...

【问题讨论】:

  • 随着列表变大,您希望行为是什么?也就是说,您如何决定哪些列应该放在最前面?
  • @BrenBarn:无论列表有多大,前 3 列都应该是 [x, y, z]

标签: python sorting pandas dataframe


【解决方案1】:

如果您知道要按特定顺序排列几列,只需在所有列和预先排序的列之间设置差异,然后调用reindex

In [13]: cols = list('xacybz')

In [14]: df = DataFrame(randn(10, len(cols)), columns=cols)

In [15]: preordered = list('xyz')

In [16]: new_order = preordered + list(df.columns - preordered)

In [17]: new_order
Out[17]: ['x', 'y', 'z', 'a', 'b', 'c']

In [18]: df.reindex(columns=new_order)
Out[18]:
       x      y      z      a      b      c
0 -0.012  0.949 -0.276 -0.074 -0.054  0.541
1  0.994  1.059 -0.158  0.267 -0.590  0.263
2 -0.632 -0.015 -0.097 -1.904 -1.351 -1.105
3 -0.730 -0.684 -0.226  2.664 -0.385  1.727
4  0.891 -0.602  3.426  1.529  0.853 -0.451
5 -0.471  0.689  1.170 -0.635 -0.663  0.180
6  1.536  0.793  1.461  0.723 -0.795 -1.094
7  0.417  0.787  1.676  1.563  1.412  0.398
8  0.378  1.436 -0.024  0.293  0.655 -0.113
9 -0.159 -0.416 -1.526  0.633 -0.780 -0.613

preorder 的元素出现的顺序无关紧要:

In [25]: shuffle(df.columns.values)

In [26]: df
Out[26]:
       b      a      z      c      x      y
0 -0.054 -0.074 -0.276  0.541 -0.012  0.949
1 -0.590  0.267 -0.158  0.263  0.994  1.059
2 -1.351 -1.904 -0.097 -1.105 -0.632 -0.015
3 -0.385  2.664 -0.226  1.727 -0.730 -0.684
4  0.853  1.529  3.426 -0.451  0.891 -0.602
5 -0.663 -0.635  1.170  0.180 -0.471  0.689
6 -0.795  0.723  1.461 -1.094  1.536  0.793
7  1.412  1.563  1.676  0.398  0.417  0.787
8  0.655  0.293 -0.024 -0.113  0.378  1.436
9 -0.780  0.633 -1.526 -0.613 -0.159 -0.416

In [27]: new_order = preordered + list(df.columns - preordered)

In [28]: new_order
Out[28]: ['x', 'y', 'z', 'a', 'b', 'c']

【讨论】:

  • 请注意,如果 xyz 未按该顺序出现在原始列表中,这将失败。 (从问题上看不清楚这是否是需要处理的案件。)
  • @Phillip Cloud:x、y 和 z 实际上会在我每次运行脚本时以随机顺序出现,我实际上使用 x、y 和 z 来简化列名,但实际上它们应该,比这更具描述性。即使使用 [x, y, z] 以外的列名,您的代码也能正常工作吗?
  • @Phillip Cloud:太好了!谢谢!
【解决方案2】:

首先构建您的新列:

new_cols = ['x', 'y', 'z'] + [c for c in df.columns if c not in ['x', 'y', 'z']]

然后做:

new_df = df.reindex(columns=new_cols)

【讨论】:

  • 使用['x', 'y', 'z'] + list(df.columns - set(['x', 'y', 'z'])) 可能会更快,因为Indexes 的功能类似于sets。
  • 我认为这种方式更具可读性,性能在这里应该不是问题,但感谢您的建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-13
  • 2022-07-19
  • 1970-01-01
相关资源
最近更新 更多