Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeError: Cannot index by location index with a non-integer key in for loop

While touring the "class" column, I want to change the value to "01" if the data value is "one", "02" if it is "two", and "03" if it is "three", what’s the problem?

# Import Packages
import pandas as pd 
import numpy as np
import seaborn as sns

# dataset upload
df = sns.load_dataset("titanic")
df = df.rename(columns={'pclass':'passenger_class','sex':'gender','age':'old'})
for x in df['class']:
    if df.iloc[x] == 'First':
      print('01')
    elif df.iloc[x] == 'Second':
      x = '02'
    elif df.iloc[x] =='Third':
      x = '03'
df

Get an error:

TypeError: Cannot index by location index with a non-integer key

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As outlined in comment, pandas.DataFrame.iloc only takes integers as indexers. Or, given how you iterate over df['class'], it turns out that your xs are strings of characters. Hence the TypeError you get.

That being said, if you want to replace your occurrence by something else, what about using pandas.Series.map, as follows:

>>> df['class'].map({'First': '01', 'Second': '02', 'Third': '03'})
0      03
1      01
2      03
3      01
4      03
       ..
886    02
887    01
888    03
889    01
890    03
Name: class, Length: 891, dtype: category
Categories (3, object): ['01', '02', '03']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading