我有一个列,其中包含各种大小的列表,但项目数量有限.

print(df['channels'].value_counts(), '\n')

输出:

[web, email, mobile, social]    77733
[web, email, mobile]            43730
[email, mobile, social]         32367
[web, email]                    13751

所以我想要的是网络、邮箱、移动和社交的总次数.

这些应为:

web =    77733 + 43730 + 13751            135,214
email =  77733 + 43730 + 13751 + 32367    167,581
mobile = 77733 + 43730 + 32367            153,830
social = 77733 + 32367                    110,100

我try 了以下两种方法:

sum_channels_items = pd.Series([x for item in df['channels'] for x in item]).value_counts()
print(sum_channels_items)

from itertools import chain
test = pd.Series(list(chain.from_iterable(df['channels']))).value_counts()
print(test)

这两种方法都会失败,并出现相同的错误(仅显示第二个错误).

Traceback (most recent call last):
  File "C:/Users/Mark/PycharmProjects/main/main.py", line 416, in <module>
    test = pd.Series(list(chain.from_iterable(df['channels']))).value_counts()
TypeError: 'float' object is not iterable

推荐答案

一个选项是先计算explode,然后计算值:

out = df['channels'].explode().value_counts()

另一种可能是使用collections.Counter.请注意,错误表明列中缺少值,因此可以先删除它们:

from itertools import chain
from collections import Counter
out = pd.Series(Counter(chain.from_iterable(df['channels'].dropna())))

Python-3.x相关问答推荐

根据样本量随机 Select 组内样本

为什么我必须在绘制椭圆时代码等于两次?''

Python:字典和列表:在列表字典中搜索子列表的有效方法

将f-字符串放置在f-字符串内

regexp多重前瞻行为的解释

PANDAS中当前数据帧的匹配与更新

合并两个数据帧并对某些总和进行求和

Python - 根据条件附加 NULL 值

基于Pandas列动态创建分箱,以使观测值数量或计数占总计数的1%.

找到在指定列的另一个分组中存在重复的行.

如何在带有 GUI 的 python 游戏中设置回答时间限制?

Pytorch 的随机 Select ?

Visual Studio Code 中的 Python 3.x 类型提示

PySpark python 问题:Py4JJavaError: An error occurred while calling o48.showString

sys.stdin.readline() 和 input():读取输入行时哪个更快,为什么?

使用 Sympy 方程进行绘图

使用 Sublime Text 3 在 Python 3 中打印 UTF-8

如何使用 d.items() 更改 for 循环中的所有字典键?

BeautifulSoup 的 Python 3 兼容性

python 3的蓝牙库