简体   繁体   English

Python Pandas DataFrame通过列索引而不是名称进行列调用?

[英]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: 所以在这里,我将一个csv文件导入python,然后尝试对第一列做一些操作:“类型”,但是我一直收到消息:

"AttributeError: 'DataFrame' object has no attribute 'Type' ". “ AttributeError:'DataFrame'对象没有属性'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; 这是DataFrame的样子;

     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. 您的“ Type列的第一个字符不是ascii。 It's '\' . '\'

Here's a way to strip non-ascii from your column names. 这是从列名中删除非ASCII的方法。

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

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

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