将包含多行数据的单元格拆分为每个 ID 的单独行 Pandas

split a cell with multiline data into separate rows per ID Pandas

我有一个数据框 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中有什么好的方法可以得到这样的输出吗?

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

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