df.loc[df.gender=='boy',:]['names'] = df.loc[df.gender=='boy',:]['names'].replace(',','/',regex=False)
print df (result)
gender names
0 boy bob, joe
1 boy john, nick
2 girl sarah, ally
3 girl maria, sally
df['names'] = df.loc[df.gender=='boy',:]['names'].replace(',','/',regex=False)
print df (result)
gender names
0 boy bob, joe
1 boy john, nick
2 girl NaN
3 girl NaN
我也尝试了df['names'].str.replace(',','/',regex=False,inplace=True)
,但是收到了错误消息
TypeError:replace()得到了意外的关键字参数'inplace'。
所需结果
gender names
0 boy bob/ joe
1 boy john/ nick
2 girl sarah, ally
3 girl maria, sally
答案 0 :(得分:1)
使用:
df.loc[df.gender=='boy','names'] = df.names.str.replace(',','/')
>>> df
gender names
0 boy bob/ joe
1 boy john/ nick
2 girl sarah, ally
3 girl maria, sally
答案 1 :(得分:1)
numpy的“ put”和“ where”方法-比df.loc方法快一点:
import numpy as np
np.put(df.names, np.where(df.gender == 'boy')[0], df.names.str.replace(',', '/'))