如何使用id连接数据帧行中的字符串?

2024-05-29 04:18:18 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的数据集的一个例子

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

Tags: of数据reportidissentencesleftat
1条回答
网友
1楼 · 发布于 2024-05-29 04:18:18

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

相关问题 更多 >

    热门问题