【问题标题】:split a cell with multiline data into separate rows per ID Pandas将具有多行数据的单元格拆分为每个 ID Pandas 的单独行
【发布时间】:2019-09-15 03:32:45
【问题描述】:

我有一个数据框df,其中一列包含多行换行文本:

df = pd.DataFrame({'ID': ['1','3', '3'], \
                   'code_description': ['N1.12 - some description - further details of the case\nR31 - customer not satisfied,  (case processed)', '"C3.42 - some description - further details of the case\nL91.29 - some description : case processed"','"O20.12 - some description - further details of the case\nZ30.00 - some description / case further details\nL20 - some description  "'], \
                   'postcode': ['1037', '2512','2512'], \
                   'age': ['34', '56','56']})

我想拆分存储在code_description 列中的多行数据,并且只想获取 N1.12 或 R31 等代码,并且每个 ID 每行只获取一个代码。同时,我想将其他列保留在数据框中,但我不知道如何获得它。

我尝试使用 str.split() 方法来拆分换行符,然后使用相同的方法来分隔代码。我做了以下事情:

df['code_description'].str.split("\n", expand=True).stack() 之后使用 df['code_description'].str.split(" - ").str[0] 提取代码。但是使用这种方法,我会丢失与ID 和其他列(例如postcodeage)相关的信息。

我想要的输出如下:

   ID code_description  postcode  age
0   1            N1.12      1037   34
1   1              R31      1037   34
2   3            C3.42      2512   56
3   3           L91.29      2512   56
4   3           O20.12      2512   56
5   3           Z30.00      2512   56
6   3              L20      2512   56

有没有什么好的方法可以在 Pandas 中获得这样的输出?

【问题讨论】:

    标签: pandas split python-3.5 pandas-groupby


    【解决方案1】:
    sr = df.code_description.str.extractall(
        re.compile('(?P<extracted_code_description>[0-9A-Z\.]+)\s-\s'))
    
    sr = sr.set_index(sr.index.droplevel(1))
    
    result = pd.merge(left=df, right=sr, left_index=True, right_index=True, how='left')
    
    print(result[['ID', 'extracted_code_description', 'postcode', 'age']])
    

    输出:

      ID extracted_code_description postcode age
    0  1                      N1.12     1037  34
    0  1                        R31     1037  34
    1  3                      C3.42     2512  56
    1  3                     L91.29     2512  56
    2  3                     O20.12     2512  56
    2  3                     Z30.00     2512  56
    2  3                        L20     2512  56
    

    您可能需要改进其中的正则表达式,以普遍适用于您的所有情况。

    【讨论】:

    • 谢谢。它适用于小型数据集。我仍然需要在完整的数据集上对其进行测试。
    • 正则表达式确实是关键。
    猜你喜欢
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-30
    • 1970-01-01
    • 2017-02-05
    相关资源
    最近更新 更多