Как объединить строки в строках идентификаторов использования данных? - PullRequest
2 голосов
/ 30 сентября 2019

Вот пример моего набора данных.

d={'Report id': [0, 0, 1, 1], 'sentences': ['There is also a faint ground glass nodule. ', 'Other two ill  defined, small ground glass lesions are seen.', 'There is a small nodule at medial aspect of left breast, measured 11 mm in size.', 'Two heterogeneous enhancing lesions at lateral segment of left lobe']}
df1 = pd.DataFrame(data=d)

Я хочу объединить строки фрейма данных на основе идентификатора отчета, который начинается с 0. Если строки имеют одинаковый идентификатор отчета, онследует объединить в один ряд. Ниже приведены мои ожидаемые результаты.

dd = {'Report id': [0, 1], 'sentences': ['There is also a faint ground glass nodule. ' 'Other two ill  defined, small ground glass lesions are seen.', 'There is a small nodule at medial aspect of left breast, measured 11 mm in size.' 'Two heterogeneous enhancing lesions at lateral segment of left lobe']}
df2 = pd.DataFrame(data=dd)

Я пытался присоединиться или объединить, как это. Пожалуйста, помогите!

res = pd.concat(df["sentences"], on=['Report id'])

1 Ответ

2 голосов
/ 30 сентября 2019

Использование groupby с apply

Пример:

d={'Report id': [0, 0, 1, 1], 'sentences': ['There is also a faint ground glass nodule. ', 'Other two ill  defined, small ground glass lesions are seen.', 'There is a small nodule at medial aspect of left breast, measured 11 mm in size.', 'Two heterogeneous enhancing lesions at lateral segment of left lobe']}
df1 = pd.DataFrame(data=d)
print(df1.groupby('Report id')['sentences'].apply(" ".join))

Выход:

Report id
0    There is also a faint ground glass nodule.  Ot...
1    There is a small nodule at medial aspect of le...
Name: sentences, dtype: object
...