【问题标题】:Subset columns and reorder子集列和重新排序
【发布时间】:2020-09-16 15:00:26
【问题描述】:

我想对列重新排序并选择我想要的列。
例如,如果列名称为 ABCD
我知道简单的方法是:

# 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


    【解决方案1】:

    您将 numpy 的 np.r_ 作为 python 等效于连接索引和切片对象的子集。与subset(df, select = c(4, 3 , 1:2, 5:50, 55:100)) 类似,您可以这样做:

    df.iloc[:, np.r_[4, 3, 1:2, 5:50, 55:100]] 
    

    【讨论】:

    • @anky 是什么意思?
    • 可能是df.iloc[:, np.r_[...]]?
    • df = subset(df, select = c(4, 3 , 1, 2)) == df.iloc[:,np.r_[3,2,0,1]]可能对R不熟悉
    • 如果我不确定有多少变量,是否可以通过df.iloc[:, np.r_[4, 3, 1:2, 5:]] 重新排序到最后一列?我试过但失败了……也许错过了什么
    • df.iloc[:, np.r_[4, 3, 1:2, 5:df.shape[1]]]@peter ?
    猜你喜欢
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-13
    • 2019-07-20
    • 1970-01-01
    • 2015-08-11
    相关资源
    最近更新 更多