我有一个相当宽的 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] 删除。
我来说两句