简体   繁体   中英

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

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 x s 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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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