Nasri
Nasri

Reputation: 545

How to replace a string in a dataframe column with another in Python Pandas?

I have a dataframe called df_cv with column that contains this string _log. I would like to delete _log from the name of each column in a dataframe So i didlike this :

modify_cols=[]
for c in df_cv.columns:
    if c.find("_log") != -1:
        modify_cols.append(c)

for c in modify_cols:
     c = c.replace('_log',' ')

But it didn't work , there is no error message but the comluns name doesn't change.

Any idea please to help me?

Thanks

Upvotes: 1

Views: 110

Answers (4)

dodopy
dodopy

Reputation: 169

= makes the reference to c becomes a new string, but the string referenced by the modify_cols is still the original. and because of string is immutable, so you can not do like this:

s = [['a_log'], ['b_log']]
for i in s:
    # i reference to the mutable list
    i[0] = i[0].replace('_log', '')
# now s is [['a'], ['b']]

you can use list comprehension:

modify_cols = [c.replace('_log',' ') for c in modify_cols]

Upvotes: 0

jezrael
jezrael

Reputation: 863631

Use str.replace:

df_cv = pd.DataFrame(columns=['col1','col2_log','1_log'])
df_cv.columns=df_cv.columns.str.replace('_log', '')
print (df_cv)
Empty DataFrame
Columns: [col1, col2, 1]
Index: []

Upvotes: 3

Beri
Beri

Reputation: 11620

You should collect results in a collection, or at least process them

modified_cols=[]
for c in modify_cols:
     modified_cols.append(c.replace('_log',' '))

Or shorter version, using list comprehensions:

my_list = [c.replace('_log',' ') for c in df_cv.columns if c.find('_log')!=-1]

Otherwise you will lost each c variable after each loop block.

Upvotes: 0

Sociopath
Sociopath

Reputation: 13426

Use list-comprehension:

df_cv.columns = [i.replace("_log","") for i in df_cv.columns]

Upvotes: 0

Related Questions