首页 > 解决方案 > 全新的数据科学——确保我理解集合

问题描述

我正在尝试将字母数字代码分配给数据框中的对象,我想知道我是否走在正确的轨道上。任务是根据 NTEE 指定对组织列表进行分类。例如,任何可以被视为医疗保健的东西都将获得“E”名称和基于更具体因素的数字名称。不过,刚开始时,我想为医疗保健创建一个可能的标志列表。基于我对python非常有限的工作知识,我想出了这个:

healthcare = {'healthcare', 'health care', 'health', 'hospital', 'medical'}
for x in healthcare:
    new_healthcare = ('E')
    print(new_healthcare)

这种给了我我正在寻找的东西。这打印

E
E
E
E
E
E

我想做的下一件事是将其应用于数据框中的特定列“A”,并在“A”包含集合中的任何值的任何行中创建一个包含“E”的新列“B”卫生保健'。所以有两个问题:1)对于我正在运行的非常简单的代码,是否有更简单的方法来产生相同的结果;2)我们如何能够通过数据集中的特定列运行此循环并使用它来创建新列?

标签: pythondataframeloopsdictionaryset

解决方案


这根本与集合没有太大关系。您需要根据 column 的值查找A代码的值。

假设您有一个像这样的数据框:

    org         type
0   Hospital1   hospital
1   Hospital2   hospital
2   UrgentCare1 healthcare
3   Doctor1     medical
4   Bookstore1  business

代码:

l = [{'org': 'Hospital1', 'type': 'hospital'}, {'org': 'Hospital2', 'type': 'hospital'}, {'org': 'UrgentCare1', 'type': 'healthcare'}, {'org': 'Doctor1', 'type': 'medical'}, {'org': 'Bookstore1', 'type': 'business'}]
df = pd.DataFrame(l)

您可以创建一个查找字典,其中键是您要查找的项目,值是您想要的结果。例如:

code_lookup = {
        'healthcare': 'E', 
        'health care': 'E',
        'health': 'E', 
        'hospital': 'E', 
        'medical': 'E',
        'business': 'B',
        'other': 'O'
     }

您可以将其转换为自己的数据框:

code_lookup_df = pd.DataFrame.from_dict(code_lookup, orient='index', columns=['Designation'])

这使:

            Designation
healthcare            E
health care           E
health                E
hospital              E
medical               E
business              B
other                 O

然后,您可以简单地在 Designation 列的值中查找code_lookup_dforiginal 中的值df["type"],并将其分配给Designation原始数据框中的列:

df['Designation'] = code_lookup_df.loc[df["type"], "Designation"].to_list()

df就是现在:

           org        type Designation
0    Hospital1    hospital           E
1    Hospital2    hospital           E
2  UrgentCare1  healthcare           E
3      Doctor1     medical           E
4   Bookstore1    business           B

推荐阅读