我想检查CSV文件中的列是否存储了等于给定输入的任何数据。
I have a csv file which I'll call myFile.csv
,
I'm using pandas
to read it as follows:
import pandas as pd
...
path = r'C:\Users\...\myFile.csv'
df = pd.read_csv(path)
One of the columns I'm trying to read data from has the heading Country/Region
. What I'm trying to do is check whether Country/Region
contains any rows with the value 'someRegion'
region = 'someRegion'
for item in df.Country/Region:
if item == region:
#doSomething
我遇到的问题是,当我这样做时,出现以下错误:
AttributeError: 'DataFrame' object has no attribute 'Country'
有没有办法在不将CSV文件中列标题的名称更改为没有正斜杠的情况下起作用,因为这不是一种选择?
(I'm using the latest version of pandas
and python 3.7.7
)
您可以通过以下方式引用列:
Python不会按照您想要的方式解释以下代码行,因此会出现错误:
Python解释器认为“ /”符号是除法运算符,而不是列名称的一部分。
如果列名包含充当运算符的字符,例如“ /”,则需要使用[]括号表示法来寻址DataFrame。