I want to check whether a column in a CSV file is storing any data that is equal to a given input.
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
The issue I'm having is that when I do this I get the following error:
AttributeError: 'DataFrame' object has no attribute 'Country'
Is there any way for this to work without changing the name of the column heading in the CSV file to something without a forward slash as this is not an option?
(I'm using the latest version of pandas
and python 3.7.7
)
you can reference column in following way:
In [44]: for item in df['country/region']:
...: if item == region:
...: #do something
...:
Python won't interpret the following line of code in the way you want it to, hence the error:
for item in df.Country/Region:
The Python Interpreter thinks the '/' symbol is a division operator and not part of the column name.
If the name of the column contains a character that acts as an operator, like "/", you need to address your DataFrame using the [] bracket notation.
if "region" in df["Country/Region"]:
pass
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.