简体   繁体   中英

Python Pandas DataFrame column calls by column index but not name?

So here I import a csv file into python and then try to do something with the first column: 'Type', but I keep getting the message:

"AttributeError: 'DataFrame' object has no attribute 'Type' ".

Printing the column by name does not work, but printing it by location does. Why does referencing it by name not work? It works for all other columns.

import pandas as pd
data = pd.read_csv('ResturantData.csv', sep=',', index_col=False) 
df = pd.DataFrame(data=data)

print(df.head())
print(df.columns)

print(df.iloc[:, 0])    #Works! 
print(df.Type)          #Doesn't work :/
print(df['Type'])       #Doesn't work :/

Here is what the DataFrame looks like;

     Type  Size  Bill  Tip
0  Dinner     5   126   12
1  Dinner     4   103   12
2  Dinner     4    94   11
3  Breakfast  4    87   10
4  Dinner     4    76    7

Thanks!

The first character of your Type column isn't ascii. It's '\' .

Here's a way to strip non-ascii from your column names.

df.rename(columns=lambda x: ''.join([y for y in x if ord(y) < 128]), inplace=True)

df.Type

0       Dinner
1       Dinner
2       Dinner
3    Breakfast
4       Dinner
Name: Type, dtype: object

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.

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