Replace row in pandas df column

I have a data frame in pandas with columns named "string_string", I'm trying to rename them by deleting "_" and the next row. For example, I want to change "12527_AC9E5" to "12527". I tried to use various replacement options, and I can replace a certain part of the string (for example, I can replace all the characters with "_"), but when I use wildcards, I do not achieve the desired result.

Below are some things that I thought would work, but not. If I remove the wildcards that they work (i.e. they replace _).

df = df.rename(columns=lambda x: x.sub('_.+', ''))

df.columns = df.columns.str.replace('_.+','')

Any help is appreciated

+5
source share
1 answer

"_" . :

df = df.rename(columns={col: col.split('_')[0] for col in df.columns})
+13

Source: https://habr.com/ru/post/1614604/


All Articles