【发布时间】:2016-08-23 23:37:49
【问题描述】:
我有一个数据框,并希望根据每个键具有多个值的字典重命名列。字典键具有所需的列名,并且值包含可能的旧列名。列名没有模式。
import pandas as pd
column_dict = {'a':['col_a','col_1'], 'b':['col_b','col_2'], 'c':'col_c','col_3']}
df = pd.DataFrame([(1,2.,'Hello'), (2,3.,"World")], columns=['col_1', 'col_2', 'col_3'])
用键替换文本的功能
def replace_names(text, dict):
for key in dict:
text = text.replace(dict[key],key)
return text
replace_names(df.columns.values,column_dict)
在列名上调用时出错
AttributeError: 'numpy.ndarray' object has no attribute 'replace'
还有其他方法吗?
【问题讨论】: