I am trying to print a single column name and the corresponding values for that column in Python from a CSV file using pandas. I am able to print the column names, but when I then try to print just one of the columns with the following code:
import pandas as pd
df = pd.read_csv('pokemon_data.csv')
print(df['name'])
I then get these errors:
Updated: I see that the error is a "key error" however a key named "Name" should exist as it does when I run:
print(df.columns)
with output:
Index(['#,Name,Type 1,Type 2,HP,Attack,Defense,Sp. Atk,Sp. Def,Speed,Generation,Legendary'], dtype='object')
CodePudding user response:
"KeyError : name" It seems like you don't have a name column.
CodePudding user response:
If "Name" exists like you said, you should use "Name". The column names are case sensitive.
CodePudding user response:
To extend my comment below your question - your next issue is that the output of print(df.columns)
, which is Index(['#,Name,Type 1,Type 2,HP,Attack,Defense,Sp. Atk,Sp. Def,Speed,Generation,Legendary'], dtype='object')
, is indicative that you only have 1 column.
The name of that 1 column is '#,Name,Type 1,Type 2,HP,Attack,Defense,Sp. Atk,Sp. Def,Speed,Generation,Legendary'
. Maybe there is an issue with your .csv file, or perhaps messing with the read_csv
settings (see docs here) may help. For example, changing the separator/delimiter to whatever your .csv file is using.