Home > Software engineering >  How to change values in a string column of a Pandas dataframe?
How to change values in a string column of a Pandas dataframe?

Time:05-30

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'"

CodePudding user response:

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

CodePudding user response:

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
  • Related