python - 分组并附加列表和字符串

标签 python pandas

我正在尝试对“value_1”列中的值进行分组。但我的最后一个专栏是由列表组成的。当我尝试使用“value_1”列进行分组时,由列表组成的列消失了。

数据框:

 value_1:        value_2:           value_3:               list: 
 american     california, nyc      walmart, kmart      [supermarket, connivence] 
 canadian         toronto            dunkinDonuts      [coffee]
 american          texas                               [state]
 canadian                             walmart          [supermarket] 
   ...              ...                 ...              ....

我的预期输出是:

value_1:        value_2:              value_3:             list: 
american   california, nyc, texas   walmart, kmart      [supermarket, connivence, state] 
canadian         toronto         dunkinDonuts, walmart  [coffee, supermarket]

谢谢!

最佳答案

你可以 groupby value_1 并使用以下函数聚合包含字符串的列:

def str_cat(x):
    return x.str.cat(sep=', ')

并使用 GroupBy.sumlist 列中附加列表:

df.replace('',None).groupby('value_1').agg({'list':'sum', 'value_2': str_cat,
                                            'value_3': str_cat})

                        list                       value_2  \
value_1                                                              
american  [supermarket, connivence, state]  california, nyc, texas   
canadian             [coffee, sipermarket]          toronto, texas   

                    value_3  
value_1                                 
american  walmart, kmart, dunkinDonuts  
canadian         dunkinDonuts, walmart  

关于python - 分组并附加列表和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54944344/

相关文章:

python - 使用 websockets 和 asyncio 监听多个套接字

python - 如何在 Python 中使用可选参数正确执行 SQL 查询?

python - Pandas :在分隔符上拆分一列,并获得唯一值

从 Pandas DataFrame 调用列数据时出现 Python 错误

python - 漂亮的 Python 装饰器

python - 在开发模式下安装 Flask 应用程序

python - 在 NITE2 python 绑定(bind)中创建 UserTracker 崩溃

python - 按用户索引计算 pandas 数据框中丢失的行数

python - 来自趋势 python 的时间序列拟合值

Pandas 重新采样数据框并将日期时间索引保留为一列