Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Index' object is not callable in python

Tags:

python

pandas

I am new to python. Can someone explain what happened when I try to get index information after reading the csv file?

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.

dataframe

But when I try to get the index information using df.index(), I got an error, saying Index object is not callable.

like image 743
Yue Avatar asked Jun 06 '26 14:06

Yue


1 Answers

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).

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))

like image 186
Evan Nowak Avatar answered Jun 09 '26 03:06

Evan Nowak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!