简体   繁体   English

按 pandas python 中的列号读取 csv 文件

[英]Read csv file by column number in pandas python

I have a csv file with hundreds of columns, each column with long names.我有一个包含数百列的 csv 文件,每列都有长名称。 Is there a way to read only the specified columns by number like column number 2 to 5 and column number 50 to 71. I know I can read specified columns by the column names using the 'usecols' parameter but can I specify the column numbers to get the desired columns?有没有办法按列号 2 到 5 和列号 50 到 71 只读取指定的列。我知道我可以使用“usecols”参数按列名读取指定的列,但我可以指定列号到得到所需的列?

If we already know which column to read如果我们已经知道要阅读哪一column

yourdf = pd.read_csv('your file', usecols =[2,3,4,5], header = None)

You can read the whole csv in pandas to avoid any confusions:您可以在 pandas 中阅读整个 csv 以避免任何混淆:

df = pd.read_csv(filename)

Then use iloc to get the specific columns, like this:然后使用iloc获取特定列,如下所示:

df.iloc[:, 2:6] # This will give you all rows for columns 2 to 5

OR, if you want to filter directly while reading from csv或者,如果您想在读取 csv 时直接过滤

From the pd.read_csv docs:pd.read_csv文档:

Return a subset of the columns.返回列的子集。 If list-like, all elements must either be positional (ie integer indices into the document columns) or strings that correspond to column names provided either by the user in names or inferred from the document header row(s).如果类似列表,则所有元素必须是位置的(即 integer 索引到文档列)或对应于用户在名称中提供的列名或从文档 header 行推断的列名的字符串。 For example, a valid list-like usecols parameter would be [0, 1, 2] or ['foo', 'bar', 'baz'].例如,一个有效的类似列表的 usecols 参数将是 [0, 1, 2] 或 ['foo', 'bar', 'baz']。

You can use usecols with indexes(numbers) or strings.您可以将usecols与索引(数字)或字符串一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM