重命名熊猫列的编程方式,插入'_'

公里

我有一个相当宽的 Pandas DataFrame,有 300 列。space单词之间有几个列名。我想spaces_.

我不能使用df.rename,因为我必须指定 300 个列名中的每一个。寻找一种在 python 中执行此操作的编程方式。以下是一些可以使用的示例数据:

import pandas as pd

df = pd.DataFrame({
                   'col 1': [1],
                   'col 2': [2],
                   'col 3': [3]
                 })
百利绿

您可以为此使用生成器表达式和字符串方法replace()

df = pd.DataFrame({
                   'col 1': [1],
                   'col 2': [2],
                   'col 3': [3]
                 })

df.columns = (x.replace(' ', '_') for x in df.columns)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章