计算整个 DataFrame 中值的数量 [英] Count number of values in an entire DataFrame
问题描述
我目前有 50 列和大约 50000 行的 DataFrame.我试图找到一个值(例如 2)在整个 DataFrame 中出现的总次数.
I currently have DataFrame with 50 columns and around 50000 rows. I'm trying to find the total amount of times a value (e.g. 2) appears in the entire DataFrame.
DataFrame 只包含 0 到 7 之间的值.我可以使用这个为单列执行代码:
The DataFrame only contains values between 0 to 7. I am able to execute the code for a single column using this:
print(df['col1'].value_counts())
然后我尝试创建一个如下所示的 for 循环:
I then attempted to create a for loop like the one shown below:
for cols in df:
print(df[cols].value_counts())
这是可行的,但它会将其打印为每列的单独结果.
This works, but it prints it out as individual results for each column.
我没有将结果按列拆分,而是尝试获得如下所示的结果,但要合并 DataFrame 中的所有列,而不仅仅是 1 列.
Instead of having the results split up per column, I'm trying to get something like what's shown below, but for all the columns in the DataFrame combined and not just 1 column.
val no.
7.0 165
3.0 127
5.0 118
6.0 112
2.0 98
4.0 88
1.0 64
0.0 21
Name: col1, dtype: int64
任何帮助将不胜感激!
推荐答案
对于特定值:
(df.values == 2).sum()
或所有:
np.unique(df.values, return_counts=True)
这篇关于计算整个 DataFrame 中值的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!