python - Pandas 合并相似行的列值

标签 python pandas

我有一个数据框,其中包含具有唯一列值的相似行。如果任何行具有重复的值组合,我需要将唯一值连接到每行的列中。

示例数据

| program | subject | course | title |
|:------- |:------- |:------ |:----- |
|music    | eng     | 101    | 000   |
|music    | math    | 101    | 123   |
|music    | eng     | 102    | 000   |
|music    | math    | 101    | 456   |
|art      | span    | 201    | 123   |
|art      | hst     | 101    | 000   |
|art      | span    | 201    | 456   |
|art      | span    | 202    | 000   |

需要的数据

| program | subject | course | title.   |
|:------- |:------- |:------ |:-----    |
|music    | eng     | 101    | 000      |
|music    | math    | 101    | 123-456  |
|music    | eng     | 102    | 000      |
|music    | math    | 101    | 456-123  |
|art      | span    | 201    | 123-456  |
|art      | hst     | 101    | 000      |
|art      | span    | 201    | 456-123  |
|art      | span    | 202    | 000      |

第 2 行和第 4 行以及第 5 行和第 7 行的前三列匹配。我想连接标题,以便每行包含匹配行的标题组合。

最佳答案

让我们试试 groupby transform :

df['title'] = df.groupby(
    ['program', 'subject', 'course'], as_index=False, sort=False
)['title'].transform('-'.join)
print(df)

输出:

  program subject  course    title
0   music     eng     101      000
1   music    math     101  123-456
2   music     eng     102      000
3   music    math     101  123-456
4     art    span     201  123-456
5     art     hst     101      000
6     art    span     201  123-456
7     art    span     202      000

关于python - Pandas 合并相似行的列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67440575/

相关文章:

python - Qcut Pandas : ValueError: Bin edges must be unique

python - 如何计算两个 Pandas DataFrame 列之间的编辑距离?

python - Django 在模型中保存 JSON 数据时出错

python - Python 库 httplib2 是否使用 GET 字符串缓存 URI?

python - 在当前窗口上进行 python 自动化

python - 使用 SublimeREPL 运行 python 代码时重新使用选项卡

python - Pandas/Python 破坏 DataFrame 中的 JSON 数据

python - 在 Pandas 中调用多行

python - 如何在Python中的列表排序中获得正确的结果

python - 如何从 Pandas 数据框中的不同点选择行