具有字符串列表的Python DataFrame列不会展平

2024-04-25 01:04:39 发布

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

我在DataFrameproduction_company)中有一个列,其中列出了电影制作公司的字符串。我想搜索所有电影制作公司的所有独特事件。在

在下面的数据中,我给出了production_company中列值的示例。在

"['Universal Studios', 'Amblin Entertainment', 'Legendary Pictures', 'Fuji Television Network', 'Dentsu']"
"['Village Roadshow Pictures', 'Kennedy Miller Productions']"
"['Summit Entertainment', 'Mandeville Films', 'Red Wagon Entertainment', 'NeoReel']"
"['Lucasfilm', 'Truenorth Productions', 'Bad Robot']"
"['Universal Pictures', 'Original Film', 'Media Rights Capital', 'Dentsu', 'One Race Films']"
"['Regency Enterprises', 'Appian Way', 'CatchPlay', 'Anonymous Content', 'New Regency Pictures']"

我试图首先使用Pandas Series of lists to one series中给出的展平解决方案展平列

但是我得到了错误'TypeError: 'float' object is not iterable'

^{2}$

production_companies保存列df['production_company']

公司是一个list,为什么它把它当作float?即使是列表理解也会产生相同的错误:flattened_list = [y for x in production_companies for y in x]


Tags: 电影错误公司floatcompanyuniversallistproduction
1条回答
网友
1楼 · 发布于 2024-04-25 01:04:39

您可以使用collections.Counter来计数项目。我将任务分为三个步骤:

  1. 通过ast.literal_eval将一系列字符串转换为一系列列表。在
  2. 使用itertools.chain形成一个iterable of companies并馈送给Counter。在
  3. 使用字典理解筛选计数为1的公司。在

下面是一个演示:

from ast import literal_eval
from itertools import chain
from collections import Counter

s = df['companies'].map(literal_eval)
c = Counter(chain.from_iterable(s))
c_filtered = {k for k, v in c.items() if v == 1}

结果:

^{pr2}$

相关问题 更多 >