pandas 保留数据框熊猫中的特定列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48053654/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:00:16  来源:igfitidea点击:

Keep specific columns from a dataframe pandas

pythonpandas

提问by cottinR

I have a dataframe from an import csv using pandas. This dataframe has 160 variables and I would like to keep only 5, 9, 10, 46, 89.

我有一个来自使用 Pandas 的导入 csv 的数据框。这个数据框有 160 个变量,我只想保留 5、9、10、46、89。

I try this:

我试试这个:

dataf2 = dataf[[5] + [9] + [10] + [46] + [89]]

but I take this error:

但我接受这个错误:

KeyError: '[ 5 9 10 46 89] not in index'

回答by koPytok

If you want to refer to columns not by their names but by their positions in the dataset, you need to use df.iloc:

如果您不想通过名称而是通过它们在数据集中的位置来引用列,则需要使用df.iloc

dataf.iloc[:, [5, 9, 10, 46, 89]]

Row indices are specified before the comma, column indices are specified after the comma.

逗号前指定行索引,逗号后指定列索引。

回答by Joe Iddon

If the columns that you would like to keep are: 5, 9, 10, 46, 89, then you can index just these ones like so:

如果您想保留的列是: 5, 9, 10, 46, 89,那么您可以像这样索引这些列:

dataf2 = dataf[[5, 9, 10, 46, 89]]