Reputation: 81
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
Upvotes: 1
Views: 1330
Reputation: 6665
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']
Upvotes: 1