【发布时间】:2020-04-08 05:43:47
【问题描述】:
我正在尝试重命名数据框中的某些列。第一个问题(我解决了)是一些列名包含字符串:\xa0
您将在下面看到我将它们替换为常规空格的位置(并且我会检查前后)。
我以前用过重命名。没遇到过这个问题。
另外,在下面的代码中,如果我添加:axis=1,我会收到一条错误消息,提示意外关键字“axis”。 ?? 我认为这是因为它在下面的错误中窒息,所以它发现了轴的故障。
我的代码有什么问题?
col_names = {'Record ID': 'id',
'CESSATION YEAR': 'cease_date',
'Reason for ceasing employment': 'separationtype',
'Gender. What is your Gender?': 'gender',
'CurrentAge. Current Age': 'age',
'Employment Type. Employment Type': 'employment_status',
'Classification. Classification': 'position',
'LengthofServiceOverall. Overall Length of Service at Institute (in years)': 'institute_service',
'LengthofServiceCurrent. Length of Service at current workplace (in years)': 'role_service'
}
print(list(tafe_survey_updated), '\n')
tafe_survey_updated = tafe_survey_updated.columns.str.replace("\\xa0", " ")
print(list(tafe_survey_updated), '\n')
tafe_survey_updated = tafe_survey_updated.rename(col_names)
for col in list(tafe_survey_updated):
print(col)
print()
重要提示此问题仅在我将 \xa0 替换为空格后才开始。在此之前,重命名运行良好,但它没有更新任何包含 \xa0 的列名。
【问题讨论】:
-
试试
df.columns.str.replace(r'\\xa0', '')对我有用。 -
我试过了。它确实也解决了 \xa0 问题,但是我无法重命名列。
标签: python-3.x pandas rename