簡體   English   中英

計算 pandas 系列中的特定值

[英]Count specific values in a pandas series

我在 python 中有一個 pandas 系列。 是否有一種功能/簡單的方法來構造一個包含給定值出現次數的系列?

為了演示,假設我有以下系列: 1, 3, 1, 5, 10 我想從以下列表中計算每個值的出現次數: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 應該返回的系列是2, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1

我們做value_counts + reindex

l=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
l1=[1, 3, 1, 5, 10]
pd.Series(l1).value_counts().reindex(l,fill_value=0).tolist()
[2, 0, 1, 0, 1, 0, 0, 0, 0, 1]

使用numpy.bincount

import numpy as np
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
s = pd.Series([1, 3, 1, 5, 10])

out = list(np.bincount(s)[[l]])
out
[2, 0, 1, 0, 1, 0, 0, 0, 0, 1]

使用 map:

s = pd.Series([1, 3, 1, 5, 10])
inp_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

pd.Series(inp_list).map(s.value_counts()).fillna(0).astype(int).tolist()

或者用get列出 comp

c = s.value_counts()
[c.get(i,0) for i in inp_list]
#or [*map(lambda x: c.get(x,0),inp_list)]

[2, 0, 1, 0, 1, 0, 0, 0, 0, 1]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM