【发布时间】: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 和其他列(例如postcode 和age)相关的信息。
我想要的输出如下:
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