Reputation: 1309
Is there a way to conditionally add a space to the word "apple" in df.columns? Looking for generalised approach.
df
the_apple hut the appletree fork applehut
0 5 3 2
for x in df.columns:
if "tree" in x and "apple" in x:
x = x.replace("apple", "apple ")
Expected Output
df
the_apple hut the apple tree fork applehut
0 5 3 2
Upvotes: 1
Views: 188
Reputation: 862711
Use list comprehension with if-else
:
df.columns = [x.replace("apple", "apple ") if "tree" in x else x for x in df.columns]
print (df)
the_apple hut the apple tree fork applehut
0 5 3 2
If need repalce by dictionary only matched names by tree
string:
m = df.columns.str.contains('tree')
d = {"apple": "apple ", 'hut': ' hut '}
df.columns = df.columns.where(~m, df.columns.to_series().replace(d, regex=True))
print (df)
the_apple hut the apple tree fork applehut
0 5 3 2
Upvotes: 2