3

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.

3
  • 3
    Try df.index instead Commented Sep 15, 2017 at 2:03
  • Why are you calling it as though it were a function? It isn't, which you clearly know, because a few lines earlier is this line of code df.index.str.split(...) Commented Sep 15, 2017 at 2:09
  • Thanks. Those lines are given in the assignment, so actually I do not notice that. I am also new to python, so sorry for my stupid question. Commented Sep 15, 2017 at 19:40

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.