简体   繁体   中英

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

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

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

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