python - 如何计算列表列中列值的出现次数?

标签 python pandas series

考虑以下数据框:

    column_of_lists   scalar_col
0   [100, 200, 300]       100
1   [100, 200, 200]       200
2   [300, 500]            300
3   [100, 100]            200

所需的输出将是一个系列,表示 scalar_col 的标量值出现在列表列中的次数。

所以,在我们的例子中:

1 # 100 appears once in its respective list
2 # 200 appears twice in its respective list
1 # ...
0

我尝试了一些类似的方法:

df['column_of_lists'].apply(lambda x: x.count(df['scalar_col'])

我知道它不会工作,因为我要求它计算一个系列而不是单个值。

欢迎任何帮助!

最佳答案

使用列表理解:

df['new'] = [x.count(y) for x,y in zip(df['column_of_lists'], df['scalar_col'])]
print (df)
   column_of_lists  scalar_col  new
0  [100, 200, 300]         100    1
1  [100, 200, 200]         200    2
2       [300, 500]         300    1
3       [100, 100]         200    0

如果性能不重要使用DataFrame.apply axis=1:

df["new"] = df.apply(lambda x: x["column_of_lists"].count(x["scalar_col"]), axis=1)

#40k rows
df = pd.concat([df] * 10000, ignore_index=True)

In [145]: %timeit df["new1"] = df.apply(lambda x: x["column_of_lists"].count(x["scalar_col"]), axis=1)
572 ms ± 99.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [146]: %timeit df['new2'] = [x.count(y) for x,y in zip(df['column_of_lists'], df['scalar_col'])]
22.7 ms ± 840 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [147]: %%timeit
     ...: x = df.explode('column_of_lists')
     ...: df['counts'] = x.column_of_lists.eq(x.scalar_col).groupby(x.index).sum()
     ...: 
61.2 ms ± 306 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

关于python - 如何计算列表列中列值的出现次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75096369/

相关文章:

python - Eurostat 的 pandas 数据挖掘

python - 如何从 Python 中的负纪元创建日期时间

python - 如果模块 'example' 包含函数 'run' 和子模块 'run' ,我可以指望 'from example import run' 总是导入前者吗?

python - 检查 pandas 数据帧的最后一行是否满足条件的最佳方法是什么?

python - numpy - 给定一个数字,找到与它相加的数字,具有模糊权重

python - Pandas :从一列中为另一列中的每个唯一值获取最高值

python - 通过将函数应用于 pandas Series 来获取字典

python - 在 pandas 系列中拆分为 '||'

python - 如何使用pandas python获取数据框中每列的最大长度

python - 使用对单个元素进行操作的 lambda 表达式来过滤 pandas 系列