python - 在 python 中按数据框分组并在多列上连接字符串

标签 python pandas dataframe group-by

我有如下数据框

enter image description here

A,B,C,D
91102,1,john,
91102,2,john,
91102,3,john,
91102,1,,mary
91102,2,,mary
91102,3,,mary
91103,1,sarah,
91103,2,sarah,
91103,3,sarah,
91103,1,,khan
91103,2,,khan
91103,3,,khan

我想要按 A 列和 B 列分组,并希望获得如下所示的所需输出 enter image description here

A,B,C,D
91102,1,john,mary
91102,2,john,mary
91102,3,john,mary
91103,1,sarah,khan
91103,2,sarah,khan
91103,3,sarah,khan

我在下面尝试但没有给出所需的输出

df=df.groupby(['A', 'B'], as_index=False).agg('' .join)

最佳答案

groupby 中,您可以回填,然后取组的第一行。

df.groupby(['A','B'], as_index=False).apply(lambda x: x.bfill().iloc[0])

结果

       A  B      C     D
0  91102  1   john  mary
1  91102  2   john  mary
2  91102  3   john  mary
3  91103  1  sarah  khan
4  91103  2  sarah  khan
5  91103  3  sarah  khan

关于python - 在 python 中按数据框分组并在多列上连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73807925/

相关文章:

python-3.x - 根据其他列中的匹配项填充 `Pandas.DataFrame` 中的列

python - 将 df 保存到 excel 然后读回 df 后,Pandas 日期时间值搞砸了

python - Pandas 数据框到 excel 给出 "file is not UTF-8 encoded"

python - 像 Excel 一样对数据框列进行平均

python - 转换数据框

python - 如何将条形图转换为数据?

python - 从 PEP8 编写的 Python 文档字符串制作 API

python - Pandas 将列表列表转换为列名并附加值

python - 使用 matplotlib 创建带有回归线的箱线图

Python:数组中的条件元素