【问题标题】:Split string into two different columns based on keyword in pandas?根据熊猫中的关键字将字符串拆分为两个不同的列?
【发布时间】:2017-09-06 09:45:01
【问题描述】:

我有一个数据集包含以字符串形式作为数据类型“对象”的列“useful_crit”。

Pat_ID   Useful_crit
  1      **inclusive range**:age 35 to 75 - type 2 diabetes **exclusive range**: type 1 diabetes
  2      **inclusive range**:patients aged 21 and above **exclusive range**:patients who are mentally `

每列字符串由包含范围和排除范围两个常用词组成。现在,我想从同一个字符串中创建两列作为“包含范围”和“排除范围”。所以输出会是这样的,

Pat_ID   inclusive range                         exclusive range
 1       age 35 to 75 - type 2 diabetes     type 1 diabetes    
 2       patients aged 21 and above         patients who are mentally

如何在 python 中做到这一点?

【问题讨论】:

    标签: python regex pandas dataframe


    【解决方案1】:

    这是一种方法

    In [2519]: (df.Useful_crit.str.split('(\**inclusive\**:|\**exclusive\**:)')
                  .apply(pd.Series)[[2,4]])
    Out[2519]:
                                     2                          4
    0  age 35 to 75 - type 2 diabetes             type 1 diabetes
    1      patients aged 21 and above   patients who are mentally
    
    In [2520]: df.join(df.Useful_crit.str.split('(\**inclusive\**:|\**exclusive\**:)')
                         .apply(pd.Series)[[2,4]]
                         .rename(columns={2: 'inclusive', 4: 'exclusive'}))
    Out[2520]:
       Pat_ID                                        Useful_crit  \
    0       1  **inclusive**:age 35 to 75 - type 2 diabetes *...
    1       2  **inclusive**:patients aged 21 and above **exc...
    
                             inclusive                  exclusive
    0  age 35 to 75 - type 2 diabetes             type 1 diabetes
    1      patients aged 21 and above   patients who are mentally
    

    【讨论】:

    • 在这行代码中(df.Useful_crit.str.split('(*inclusive*:|*exclusive*:)') .apply(pd.Series)[[2,4]])...... .apply(pd.Series)[[2,4]] 会做什么?
    猜你喜欢
    • 2021-03-09
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 2016-11-01
    相关资源
    最近更新 更多