Skip to main content
 首页 » 编程设计

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

2024年12月31日25findumars

我在 DataFrame (production_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'

 17 slist =[] 
 18 for company in production_companies: 
---> 19     slist.extend(company ) 
 20  
 21  
 
TypeError: 'float' object is not iterable 

production_companies 包含列 df['production_company']

Company 是一个list 那么为什么它把它当作float 呢?即使是列表推导也会出现同样的错误:flattened_list = [y for x in production_companies for y in x]

请您参考如下方法:

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

  1. 通过 ast.literal_eval 将一系列字符串转换为一系列列表。
  2. 使用 itertools.chain 形成一个可迭代的公司并提供给 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} 

结果:

print(c_filtered) 
 
['Village Roadshow Pictures', 'Kennedy Miller Productions',  
 ... 
 'Truenorth Productions', 'Regency Enterprises']