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

时间:2019-04-25 16:22:15

标签: pandas split python-3.5 pandas-groupby

我有一个数据框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中有没有很好的方法来获得这样的输出?

1 个答案:

答案 0 :(得分: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

您可能需要在此优化正则表达式,以便普遍适用于所有情况。

相关问题