繁体   English   中英

Pandas Python 计算一列包含数字列表的次数

[英]Pandas Python Count how many times a column contains a list of numbers

假设一个数据框看起来像这样。

 . Value 0 86248 1 55265 2 52654 3 55568 4 56985 5 56855 6 79623 7 56648 ...

我想计算数字[0,1,2,3...,100000]出现在Value列中的次数,然后将结果表格化。

 . Value 0 86248 df.loc[df.Value == 0, 'Value'].count() 1 55265 df.loc[df.Value == 1, 'Value'].count() 2 52654 df.loc[df.Value == 2, 'Value'].count() 3 55568 df.loc[df.Value == 3, 'Value'].count() 4 56985 df.loc[df.Value == 4, 'Value'].count() 5 56855 df.loc[df.Value == 5, 'Value'].count() 6 79623 df.loc[df.Value == 6, 'Value'].count() 7 56648 df.loc[df.Value == 7, 'Value'].count() ... .... df.loc[df.Value ==100 000, 'Value'].count()

预期输出

 . Value Counts 0 2 0 #Count 0 1 5 0 #Count 1 2 9 1 #Count 2 3 8 2 #Count 3 4 3 0 #Count 4 5 3 1 #Count 5 6 7 0 #Count 6 7 6 1 #Count 7

我假设您的要求是:

对于 [0,1,2....100000] 中的每个 num,计算 num 在列“值”中出现的次数。

例如结果:0:出现 x 次 1:出现 x 次 ....

counts_dict = dict

for i in [1,2,.....,100000]:
    #how many rows have this value?
    count = len(df[df.value==i])

    #add this to a dictionary
    counts_dict.update({i:count})

您现在有一个字典,其中包含 [1,2,.....,100000] 中的每个值以及它们出现的次数。 为简单起见,您可以将其视为数据框:

s = pd.Series(counts_dict, name='counts')

其中 s 的索引是您的项目,而值是计数

您可以使用Series.value_counts()以及对.reindex的调用来快速解决此问题。

创建示例数据:

df = pd.DataFrame({
    "Value": [10, 8, 1, 2, 3, 10, 10, 10, 1, 1]
})

print(df)
   Value
0     10
1      8
2      1
3      2
4      3
5     10
6     10
7     10
8      1
9      1
  • 创建一个 value_range,它是我想要计数的最小值/最大值。 在这种情况下,我想查看 0-10 之间的数字在“值”列中出现的次数。
  • 然后我们使用df["Value"].value_counts()来计算该列中每个值出现的次数。
  • 最后,我们使用reindex(value_range, fill_value=0)value_counts()输出重新排序以包括最初不在“Value”列中的数字(例如reindex(value_range, fill_value=0) ),如果是这种情况它将用 0 填充那些不存在的数字(因为它们在我们的原始列中出现了 0 次)
value_range = range(0, 11) 
out = df["Value"].value_counts().reindex(value_range, fill_value=0)

print(out)
0     0
1     3
2     1
3     1
4     0
5     0
6     0
7     0
8     1
9     0
10    4
Name: Value, dtype: int64

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM