我想使用 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 之外的其他解决方案吗?
答案 0 :(得分:1)
_
)添加到不在字符串开头的大写字母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
。