python - 根据列名列表对 Pandas 数据框进行排序

标签 python pandas

这个问题在这里已经有了答案:





How to change the order of DataFrame columns?

(41 个回答)


3年前关闭。




我有一个像这样的 Pandas 数据框-

d = {'class': [0, 1,1,0,1,0], 'A': [0,4,8,1,0,0],'B':[4,1,0,0,3,1],'Z':[0,9,3,1,4,7]}
df = pd.DataFrame(data=d)

    A   B   Z   class
0   0   4   0   0
1   4   1   9   1
2   8   0   3   1
3   1   0   1   0
4   0   3   4   1
5   0   1   7   0

我有一个这样的列表- ['Z','B','class','A']
现在我想根据列名列表对我的 Pandas 数据框进行排序

因此新的数据框将具有列名称-
Z  B  class A

最佳答案

使用 reindex :

L = ['Z','B','class','A']
df = df.reindex(columns=L)

或按子集选择:
df = df[L]

关于python - 根据列名列表对 Pandas 数据框进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52608863/

相关文章:

python - 如何检查行字符串中每个字母的匹配

python - 持续获取 ImportError : Could not import settings 'myapp.settings' error

python - Pandas :根据时间间隔加入数据帧

python - 当类别是多字符串中的单个字符时创建虚拟对象

python - 有没有办法在 Bokeh 中为非选择字形设置多个不透明度?

python - pytest:使用 fixture 和 pandas dataframe 进行参数化

python - pandas timeseries DF 切片和选择

python - 在 python 中使用默认的 firefox 配置文件和 selenium webdriver

python - 谁能告诉我为什么我的代码显示错误的 pi 值?

python - 使用python正则表达式解析文本文件中的相关行组