pandas “索引”对象在python中不可调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46230592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
'Index' object is not callable in python
提问by Yue
I am new to python. Can someone explain what happened when I try to get index information after reading the csv file?
我是python的新手。有人可以解释我在阅读 csv 文件后尝试获取索引信息时发生了什么吗?
import pandas as pd
df = pd.read_csv('olympics.csv', index_col=0, skiprows=1)
for col in df.columns:
if col[:2]=='01':
df.rename(columns={col:'Gold'+col[4:]}, inplace=True)
if col[:2]=='02':
df.rename(columns={col:'Silver'+col[4:]}, inplace=True)
if col[:2]=='03':
df.rename(columns={col:'Bronze'+col[4:]}, inplace=True)
if col[:1]=='№':
df.rename(columns={col:'#'+col[1:]}, inplace=True)
names_ids = df.index.str.split('\s\(') # split the index by '('
df.index = names_ids.str[0]
df['ID'] = names_ids.str[1].str[:3]
df = df.drop('Totals')
df.head()
Then I get this dataframe.
然后我得到这个数据框。
But when I try to get the index information using df.index(), I got an error, saying Index object is not callable.
但是当我尝试使用 df.index() 获取索引信息时,出现错误,说 Index 对象不可调用。
回答by Evan Nowak
You should use "df.index", "df.index()" suggests that it is a function. "df.index" simply means that "index" is a subset of the DataFrame. You can call columns the same way (e.g. df['ID'] --> df.ID).
您应该使用“df.index”,“df.index()”表明它是一个函数。“df.index”只是意味着“index”是DataFrame的一个子集。您可以以相同的方式调用列(例如 df['ID'] --> df.ID)。
Also, it is a good habit to specify the axis in "df.drop". It defaults to 0 (index), so you will get an error if you try to drop a column without addressing this (e.g. df = df.drop('some_column', 1))
另外,在“df.drop”中指定轴是一个好习惯。它默认为 0(索引),因此如果您尝试删除列而不解决此问题,则会出现错误(例如 df = df.drop('some_column', 1))