Python:以任何大写字母拆分字符串(作为列名重命名的一部分)

时间:2017-11-28 22:47:43

标签: python regex pandas dataframe

我想使用 rename 函数重命名Pandas数据框中的列,因此我想将名称(字符串)拆分为字符串中的大写字母。 例如,我的列名称类似于'FooBar'或'SpamEggs',一列称为'Monty-Python'。我的目标是列名称,例如'foo_bar''spank_eggs'和'monty_python'。

我知道

'-'.join(re.findall('[A-Z][a-z]*', 'FooBar'))

会给我     Foo-Bar

但是这不能包含在我的重命名功能中:

df.rename(columns=lambda x: x.strip().lower().replace("-", "_"), inplace=True)

(应该在 strip lower 之间,但会返回语法错误。)

任何人都可以帮助我将代码段包含在重命名中,或者帮助我找到 findall 之外的其他解决方案吗?

1 个答案:

答案 0 :(得分:1)

  1. 删除任何不是字母的内容
  2. 将下划线(_)添加到不在字符串开头的大写字母
  3. 小写结果
  4. df.columns
    Index(['FooBar', 'SpamEggs', 'Monty-Python'], dtype='object')
    
    df.columns.str.replace('[\W]', '')\
              .str.replace('(?<!^)([A-Z])', r'_\1')\
              .str.lower()
    Index(['foo_bar', 'spam_eggs', 'monty_python'], dtype='object')
    

    这个解决方案很好地概括了。将结果分配回df.columns