【问题标题】:Hash error renaming column names in pandas哈希错误重命名熊猫中的列名
【发布时间】: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


【解决方案1】:

我想通了。

我必须这样做:

from unicodedata import normalize

new = []
print(list(tafe_survey_updated), '\n')
for col in list(tafe_survey_updated):
    new.append(normalize('NFKC', col))
tafe_survey_updated.columns = new
print(list(tafe_survey_updated))

tafe_survey_updated = tafe_survey_updated.rename(col_names, axis=1)
for col in list(tafe_survey_updated):
    print(col)
print()

【讨论】:

    【解决方案2】:

    我不是 ASCII 字符的知识,但据我了解你需要

    1. 替换列中的 \xa0 字符
    2. 重命名具有不同数量空白的列。

    我们可以这样尝试。

    df = pd.DataFrame({r'test_\xa0     data_123' : [0,1,3]})
    df.columns = df.columns.str.replace(r'\\xa0', '')
    
    
    col_names  = {'test_        data_123' : 'data'}
    #replace white space in new columns.
    new_cols = {}
    for k,v in col_names.items():
        new_cols[k.replace(' ','')] = v
    
    #do same for current columns. 
    cols = []
    for i in df.columns.tolist():
        cols.append(i.replace(' ',''))
    
    df.columns = cols
    print(df.columns.map(new_cols)
    Index(['data'], dtype='object')
    

    【讨论】:

      猜你喜欢
      • 2021-08-15
      • 2019-05-25
      • 2020-07-04
      • 2014-11-23
      • 2021-03-20
      • 2022-11-21
      • 1970-01-01
      • 2021-12-07
      相关资源
      最近更新 更多