Python 在 Pandas DataFrame 中选择多个范围的列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41256648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select multiple ranges of columns in Pandas DataFrame
提问by Alex
I have to read several files some in Excel format and some in CSV format. Some of the files have hundreds of columns.
我必须阅读几个文件,一些是 Excel 格式,一些是 CSV 格式。一些文件有数百列。
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:
有没有办法在不指定所有列名或位置的情况下选择多个列范围?例如,选择第 1 -10、15、17 和 50-100 列:
df = df.ix[1:10, 15, 17, 50:100]
I need to know how to do this both when creating dataframe from Excel files and CSV files and after the data framers created.
我需要知道在从 Excel 文件和 CSV 文件创建数据框时以及在创建数据框之后如何执行此操作。
回答by piRSquared
use np.r_
用 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])
so you can do
所以你可以做
df.iloc[:, np.r_[1:10, 15, 17, 50:100]]