简体   繁体   English

如何正确读取特定的 csv 列

[英]How to correctly read specific csv column

Hey everyone my question is kinda silly but i am new to python) I am writing a python script for c# aplication and i got kinda strange issue when i work with csv document.大家好,我的问题有点傻,但我是 python 新手)我正在为 c# 应用程序编写 python 脚本,当我使用 csv 文档时遇到了一个奇怪的问题。

When i open it it and work with Date column it works fine当我打开它并使用 Date 列时它工作正常

df=pd.read_csv("../Debug/StockHistoryData.csv")
df = df[['Date']]

But when i try to work with another columns it throws error但是当我尝试使用其他列时,它会引发错误

df = df[['Close/Last']] 

KeyError: "None of [Index(['Close/Last'], dtype='object')] are in the [columns]" KeyError:“[Index(['Close/Last'], dtype='object')] 中的任何一个都不在 [columns]”中

It says there are no such Index but but when i print the whole table it works fine and shows all columns它说没有这样的索引但是当我打印整个表格时它工作正常并显示所有列

Table Image Error image表格图像错误图像

Take a look at the first row of your CSV file.查看 CSV 文件的第一行。 It contains colum names (comma-separated).它包含列名称(逗号分隔)。 From time to time it happens that this initial line contains a space after each comma.有时,这个初始行在每个逗号之后都包含一个空格 For a human being it is quite readable and even intuitive.对于人类来说,它是相当可读的,甚至是直观的。 But read_csv adds these spaces to column names, what is sometimes difficult to discover.但是read_csv将这些空格添加到列名中,有时很难发现。

Another option is to run print(df.columns) after you read your file.另一种选择是在阅读文件后运行print(df.columns) Then look for any extra spaces in column names.然后在列名中查找任何额外的空格。

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

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