如何基于另一个数据框中的值在数据框中创建分类字段

时间:2019-02-08 00:01:49

标签: python pandas dataframe medical

我需要根据另一个数据框中的值创建一个分类变量。考虑具有医院就诊和患者ID的表1。请注意,患者可以多次去医院:

+----------+------------+
| visit_id | patient_id |
+----------+------------+
|       10 |          1 |
|       20 |          1 |
|       50 |          2 |
|      100 |          3 |
|      110 |          3 |
+----------+------------+

我需要添加一个带有1或0的新字段,以指示患者在医院就诊期间是否接受了阿司匹林,如表2所示:

+----------+------------+---------------+
| visit_id | patient_id |  medication   |
+----------+------------+---------------+
|       10 |          1 | aspirin       |
|       10 |          1 | ibuprofin     |
|       20 |          1 | codine        |
|       50 |          2 | aspirin       |
|      100 |          3 | ibuprofin     |
|      110 |          3 | acetaminophin |
|      110 |          3 | vicodin       |
+----------+------------+---------------+

您可以再次看到多个级别-您可以从医生那里获得多种药物,对吗?当然,这只是一个例子。

我试图合并表(内部联接),该表起作用了...

tab1 = pd.merge(tab1, tab2, on=['visit_id','patient_id'])

tab1['aspirin_index'] = np.where(tab1['medication'].str.contains('aspirin', 
       flags=re.IGNORECASE, regex=True, na=False),1,0)

...但是后来我得到了患者1的重复样本,该患者同时服用了阿司匹林和布洛芬。我只需要知道他们是否至少吃过一次阿司匹林。

+----------+------------+---------------+
| visit_id | patient_id | aspirin_index |
+----------+------------+---------------+
|       10 |          1 |             1 |
|       10 |          1 |             0 |
+----------+------------+---------------+

我需要到达这里...形状与表1相同,只是带有新索引。

+----------+------------+---------------+
| visit_id | patient_id | aspirin_index |
+----------+------------+---------------+
|       10 |          1 |             1 |
|       20 |          1 |             0 |
|       50 |          2 |             1 |
|      100 |          3 |             0 |
|      110 |          3 |             0 |
+----------+------------+---------------+

1 个答案:

答案 0 :(得分:2)

首先让我们设置您的示例数据。

# setup tab1 & tab2
tab1 = pd.DataFrame([[10, 1], [20, 1], [50, 2], [100, 3], [110, 3]], columns=["visit_id","patient_id"])
tab2 = pd.DataFrame([[10, 1, "aspirin"], [10, 1, "ibuprofin"], [20, 1, "codine"], [50, 2, "aspirin"], [100, 3, "ibuprofin"], [110, 3, "acetominophin"], [110, 3, "vicodin"]], columns=["visit_id","patient_id", "medication"])

有很多方法可以做到这一点。一种方法可能是仅将tab2过滤为仅阿司匹林,然后使用“左”联接将其联接至tab1,然后用0填充空值。

# filter tab2 to aspirin only
# change column name
# change to 1/0 instead of text since it now only refers to aspirin
aspirin = tab2.loc[tab2.medication=="aspirin"].copy()
aspirin.columns = ["visit_id", "patient_id", "aspirin_index"]
aspirin["aspirin_index"] = 1

# left-outer merge and fill nulls
tab1 = pd.merge(tab1, aspirin, how="left", on=["visit_id","patient_id"])
tab1.aspirin_index.fillna(0, inplace=True)
tab1["aspirin_index"] = tab1.aspirin_index.astype("int")

#  visit_id  patient_id  aspirin_index
#        10           1              1
#        20           1              0
#        50           2              1
#       100           3              0
#       110           3              0

那将为您提供一列带有“ aspirin_index”的列。这样就可以实现您的目标。

但是一次使用所有药物(包括阿司匹林)进行相同的运动呢? sklearn具有一些使它变得容易的预处理功能。

from sklearn import preprocessing

le = preprocessing.LabelEncoder()
lb = preprocessing.LabelBinarizer()

# convert each drug into a column of 1's and 0's
all_drugs = pd.DataFrame(lb.fit_transform(le.fit_transform(tab2.medication)), columns=le.classes_)

# concat with source data, aggregate, and clean up
tab2 = pd.concat((tab2.loc[:,["visit_id", "patient_id"]].copy(), all_drugs), axis=1)
tab2 = tab2.groupby(["visit_id", "patient_id"]).agg(np.sum)
tab2.reset_index(inplace=True)

#  visit_id  patient_id  acetominophin  aspirin  codine  ibuprofin  vicodin
#        10           1              0        1       0          1        0
#        20           1              0        0       1          0        0
#        50           2              0        1       0          0        0
#       100           3              0        0       0          1        0
#       110           3              1        0       0          0        1

这是一种将分类数据作为二进制特征列获取的非常常见的方法。但是它占用了空间。

如果坚持只列出一次访问的每种药物的一列,该怎么办?这样一来,您就可以进行文本搜索,而对于稀有药物而言,则没有密集的列(大多数为0)。

# create tab1 with ALL meds taken on each visit
tab2 = tab2.groupby(["visit_id", "patient_id"]).agg({"medication": list})
tab1 = pd.merge(tab1, tab2, how="left", on=["visit_id","patient_id"])

#  visit_id  patient_id                medication
#        10           1      [aspirin, ibuprofin]
#        20           1                  [codine]
#        50           2                 [aspirin]
#       100           3               [ibuprofin]
#       110           3  [acetominophin, vicodin]

# helper function to extract records for ANY drug
def drug_finder(drug):
  idx = tab1.medication.apply(lambda drugs: drug in drugs)
  return tab1.loc[idx].copy()

# find aspirin
drug_finder("aspirin")

#  visit_id  patient_id            medication
#        10           1  [aspirin, ibuprofin]
#        50           2             [aspirin]

# find ibuprofin
drug_finder("ibuprofin")

#  visit_id  patient_id            medication
#        10           1  [aspirin, ibuprofin]
#       100           3           [ibuprofin]