【问题标题】:Counting elements in a row in a multicolumn dataframe pandas在多列数据框熊猫中连续计算元素
【发布时间】:2020-10-29 09:19:21
【问题描述】:

您好,我必须计算患者一天服用多少药物。患者每天服用几种药物,数量不同。 初始数据如下所示:

df_data={'med1':['Prednisolone','Prednisolone','Folic acid','Folic acid','Prednisolone','Enbrel','Prednisolone'],
    'med2': [np.nan, np.nan, 'Folic acid','Folic acid',np.nan,'Methotrexate pill',np.nan],
    'med3':[np.nan, np.nan,'Prednisolone','Prednisolone',np.nan,'Prednisolone',np.nan]}

df_data=pd.DataFrame(df_data)
df_data

    med1            med2        med3
------------------------------------------
0   Prednisolone    NaN         NaN
1   Prednisolone    NaN         NaN
2   Folic acid  Folic acid      Prednisolone
3   Folic acid  Folic acid      Prednisolone
4   Prednisolone    NaN         NaN
5   Enbrel  Methotrexate pill   Prednisolone
6   Prednisolone    NaN         NaN

我想要得到的是为每种药物创建新列的计数。我希望它看起来像这样:

    med1       med2    med3             Prednisolone Folic acid Enbrel  Methotrexate pill
---------------------------------------------------------------------------------
0   Prednisolone        NaN       NaN              1       0       0        0
1   Prednisolone        NaN       NaN              1       0       0        0
2   Folic acid    Folic acid    Prednisolone       1       2       0.       0
3   Folic acid    Folic acid    Prednisolone       1       2       0        0
4   Prednisolone        NaN       NaN              1       0       1        1
5   Enbrel  Methotrexate pill   Prednisolone       1       0       1        1
6   Prednisolone       NaN        NaN              1       0       0        0

我不知道该怎么做。每列一个热编码然后求和?有更简单的建议吗?

【问题讨论】:

    标签: python pandas counting one-hot-encoding


    【解决方案1】:

    我们可以stack + str.get_dummies

    s=df_data.stack().str.get_dummies().sum(level=0)
       Enbrel  Folic acid  Methotrexate pill  Prednisolone
    0       0           0                  0             1
    1       0           0                  0             1
    2       0           2                  0             1
    3       0           2                  0             1
    4       0           0                  0             1
    5       1           0                  1             1
    6       0           0                  0             1
    df=df.join(s)
    

    【讨论】:

    • 太感谢了!!
    • @pink.slash yw:-) 快乐编码
    猜你喜欢
    • 2017-12-05
    • 2015-01-28
    • 1970-01-01
    • 2021-03-31
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多