【发布时间】:2020-09-16 15:00:26
【问题描述】:
我想对列重新排序并选择我想要的列。
例如,如果列名称为 A、B、C 和 D。
我知道简单的方法是:
# Python
df = df[['D', 'C', 'A', 'B']]
但是,如果有多个列,比如超过一百个变量,这种方法真的很糟糕。我找到了这个answer。
# Python
cols_to_order = ['D', 'C']
new_columns = cols_to_order + (df.columns.drop(cols_to_order).tolist())
df= df[new_columns]
但上面的并不是很灵活。
在R 中,使用subset() 是同时重新排序和子集列的不错选择。
# R
df = subset(df, select = c(4, 3 , 1, 2))
如果有很多列,我们也可以使用subset()重新排序并丢弃:
# R
# Multiple columns
# Drop columns 51 to 54
df = subset(df, select = c(4, 3 , 1:2, 5:50, 55:100))
Python有类似的功能吗?
【问题讨论】:
标签: python pandas data-manipulation