asd
asd

Reputation: 1309

Add space to column names

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

Answers (1)

jezrael
jezrael

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

Related Questions