【问题标题】:Pandas groupby() merge different lists of stringsPandas groupby() 合并不同的字符串列表
【发布时间】:2021-02-05 14:00:53
【问题描述】:

我有以下数据框。

Fruit Description
Apple ["red", "big"]
Banana ["yellow", "long"]
Banana ["elongated, twisted"]
Peach ["round"]
Apple ["round", "greenish"]

我正在尝试通过列表的串联,根据水果的描述进行分组。 我应该得到:

Fruit Description
Apple ["red", "big", "round", "greenish"]
Banana ["yellow", "long", "elongated, twisted"]
Peach ["round"]

我遵循了此处提供的解决方案:pandas groupby and join lists:

df = df.groupby('Fruit', as_index=False).agg(Description =('Description', 'sum'))

但我得到的是相互关联的列表:

Fruit Description
Apple ["red", "big"]["round", "greenish"]
Banana ["yellow", "long"]["elongated, twisted"]
Peach ["round"]

有人有解决办法吗? 谢谢!

【问题讨论】:

  • 您的 Description 值似乎是字符串,而不是列表。你检查过它的数据类型吗?
  • 确实如此。

标签: python pandas pandas-groupby


【解决方案1】:

那是因为您的 Description 列是字符串。您可以去掉[] 并求和:

 '[' + df['Description'].str[1:-1].groupby(df['Fruit']).agg(', '.join) + ']'

【讨论】:

  • 谢谢,但我想保留此列表格式吗?有可能吗?
  • 措辞像个魅力。非常感谢。
【解决方案2】:

为了保持你的列表格式,我建议在你之前运行一个命令:

import json
df['Description'] = df['Description'].apply(json.loads)
df = df.groupby('Fruit', as_index=False).agg(Description =('Description', 'sum'))

这样,Description 列中的值将是实际列表,而不是字符串。

【讨论】:

  • 在尝试您的解决方案时,我遇到以下错误 JSONDecodeError: Expecting value: line 1 column 2 (char 1)
  • 这意味着您的 Description 值之一不遵循模式 [a, b, c, d, ...]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-12
  • 2020-01-15
  • 2013-07-24
  • 2015-11-14
  • 2019-09-05
  • 2022-01-15
相关资源
最近更新 更多