Python将字符串数据重新编码为类别的方法?

Python将字符串数据重新编码为类别的方法?,python,pandas,numpy,data-cleaning,Python,Pandas,Numpy,Data Cleaning,原谅我,因为我仍在研究如何通过Python清理数据 我有一个数据集,其中有一列需要清理。它是一个包含多个语句的字符串列,但有点类似。我附上一份频率表供参考: 我尝试将.str.contains与np.where方法一起使用,但字符串值太相似,无法使用。有没有其他策略可以帮助重新编码专栏 以下是我的尝试: dm = pt_df['PAT_DECISION_MAKING'] myself = dm.str.contains('Autonomous', case = True) our_fam =

原谅我,因为我仍在研究如何通过Python清理数据

我有一个数据集,其中有一列需要清理。它是一个包含多个语句的字符串列,但有点类似。我附上一份频率表供参考:

我尝试将.str.contains与np.where方法一起使用,但字符串值太相似,无法使用。有没有其他策略可以帮助重新编码专栏

以下是我的尝试:

dm = pt_df['PAT_DECISION_MAKING']

myself = dm.str.contains('Autonomous', case = True)
our_fam = dm.str.contains('family centered', case = True)
auth1 = dm.str.contains('authority figure', case = True)
both = dm.str.contains('a.|b.', case = True)

pt_df['PAT_DECISION_MAKING'] = np.where(myself, 'Myself',
                                   np.where(our_fam, 'Family Centered',
                                            np.where(auth1, 'Authority Figure',
                                                     np.where(both, 'Multiple',
                                                              es.str.replace('-', '')))))

pt_df['PAT_DECISION_MAKING'] = pd.Categorical(pt_df.PAT_DECISION_MAKING)

它可能有助于将专栏铸造为类别,然后将其重新铸造为类别。完成此操作后,您可以使用cat.CODE轻松地转换为类别

  • 将列设置为类别数据类型
  • pt_df['PAT_DECISION_MAKING']=pt_df['PAT_DECISION_MAKING'].astype('category')

  • 选取此列并指定分类代码
  • pt_df['PAT_DECISION_MAKING']=pt_df['PAT_DECISION_MAKING'].应用(lambda x:x.cat.code)