JAEWON LEE
JAEWON LEE

Reputation: 11

How to change values in a string column of a Pandas dataframe?

import pandas as pd

names = ['Bob','Jessica','Mary','John','Mel']
births = [968,155,77,578,973]

BabyDataSet = list(zip(names,births))
df = pd.DataFrame(data = BabyDataSet, columns=['Names','Births'])

df.at[3,'Names'].str.replace(df.at[3,'Names'],'!!!')

I want to change 'John' to '!!!' without directly referring 'John'.

In this way, it notice me "AttributeError: 'str' object has no attribute 'str'"

Upvotes: 1

Views: 67

Answers (2)

BENY
BENY

Reputation: 323276

You should replace with series not single value ,single value also called assign

df['Names'] = df['Names'].str.replace(df.at[3,'Names'],'!!!')
df
Out[329]: 
     Names  Births
0      Bob     968
1  Jessica     155
2     Mary      77
3      !!!     578
4      Mel     973

Upvotes: 0

MohitC
MohitC

Reputation: 4791

import pandas as pd

names = ['Bob','Jessica','Mary','John','Mel']
births = [968,155,77,578,973]

BabyDataSet = list(zip(names,births))
df = pd.DataFrame(data = BabyDataSet, columns=['Names','Births'])

df.loc[3,'Names'] = '!!!'
print(df)

Output:

     Names  Births
0      Bob     968
1  Jessica     155
2     Mary      77
3      !!!     578
4      Mel     973

Upvotes: 1

Related Questions