I am trying to replace a string in one column with another string using .where like this:
dfn = df.where(df['name'].str.count(' ') < 2, df['name'].str.replace(' ', ' _ '), axis=1)
The right columns are found but the whole row is replaced with NaN...
Thank You
Use Series.mask
:
df = pd.DataFrame({"name": ['aaa ss d', 'a s', 'a f g g']})
m = df['name'].str.count(' ') < 2
df['name'] = df['name'].mask(m, df['name'].str.replace(' ', ' _ '))
print (df)
name
0 aaa ss d
1 a _ s
2 a f g g
Or DataFrame.loc
:
m = df['name'].str.count(' ') < 2
df.loc[m, 'name'] = df.loc[m, 'name'].str.replace(' ', ' _ ')
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.