1

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

3
  • But what do you do with c variable after? With current code it will be garbage collected. Commented Apr 3, 2019 at 11:23
  • do you mean df_cv.columns=df_cv.columns.str.strip('_log') ?? Commented Apr 3, 2019 at 11:33
  • 1
    @anky_91 - rather not, a bit dangerous, it remove all values from end _, l, o, g Commented Apr 3, 2019 at 11:35

4 Answers 4

3

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: []
Sign up to request clarification or add additional context in comments.

3 Comments

Only answer using pandas methods. Should be top answer.
@jezrael thank you very much, as usual you help me. Il apreciate!!
@Nasri - You are welcome, some problem with solution?
0

Use list-comprehension:

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

Comments

0

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.

Comments

0

= 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]

1 Comment

this focused on explaining why there is no change.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.