简体   繁体   English

替换pandas df列名中的字符串

[英]Replace string in pandas df column name

I have a dataframe in pandas, with columns named "string_string", I'm trying to rename them by removing the "_" and the following string. 我在pandas中有一个数据框,列名为“string_string”,我试图通过删除“_”和后面的字符串来重命名它们。 For example, I want to change "12527_AC9E5" to "12527". 例如,我想将“12527_AC9E5”更改为“12527”。 I've tried to use various replace options, and I can replace a specific part of the string (eg, I can replace all the "_"), but when I introduce wildcards I do not achieve the desired result. 我试图使用各种替换选项,我可以替换字符串的特定部分(例如,我可以替换所有“_”),但是当我引入通配符时,我没有达到预期的结果。

Below are some of the things I thought would work, but don't. 以下是我认为可行的一些事情,但事实并非如此。 If I remove the wild cards they work (ie, they replace the _). 如果我删除他们工作的外卡(即,他们替换_)。

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

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

Any help appreciated 任何帮助赞赏

Just split on '_' and take the first element. 只需拆分'_'并取第一个元素。 You can take advantage of dictionary comprehension: 你可以利用字典理解:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM