【问题标题】:How to concatenate strings in rows of dataframe usings ids?如何使用 id 连接数据帧行中的字符串?
【发布时间】:2019-09-30 09:26:12
【问题描述】:

这是我的数据集的一个示例。

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 开始的报告 id 连接数据框的行。如果行具有相同的报告 id,则应将其连接成一行。以下是我的预期输出。

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'])

【问题讨论】:

  • df1.groupby('Report id').sentences.agg(''.join)

标签: python string pandas dataframe string-concatenation


【解决方案1】:

groupbyapply 一起使用

例如:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 2021-02-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多