在 Pandas DataFrame 中选择多个范围的列 [英] Select multiple ranges of columns in Pandas DataFrame

查看:33
本文介绍了在 Pandas DataFrame 中选择多个范围的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须读取几个文件,有些是 Excel 格式,有些是 CSV 格式.有些文件有数百列.

I have to read several files some in Excel format and some in CSV format. Some of the files have hundreds of columns.

有没有办法在不指定所有列名或位置的情况下选择多个列范围?例如,选择第 1 -10、15、17 和 50-100 列:

Is there a way to select several ranges of columns without specifying all the column names or positions? For example something like selecting columns 1 -10, 15, 17 and 50-100:

df = df.ix[1:10, 15, 17, 50:100]

我需要知道在从 Excel 文件和 CSV 文件创建数据框时以及在创建数据框之后如何执行此操作.

I need to know how to do this both when creating dataframe from Excel files and CSV files and after the data framers created.

推荐答案

use np.r_

np.r_[1:10, 15, 17, 50:100]

array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 15, 17, 50, 51, 52, 53, 54, 55,
       56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72,
       73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
       90, 91, 92, 93, 94, 95, 96, 97, 98, 99])

所以你可以这样做

df.iloc[:, np.r_[1:10, 15, 17, 50:100]]

这篇关于在 Pandas DataFrame 中选择多个范围的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆