Statistical python list number of each element appears
using statistical Python dictionary
using the Python Counter in statistics collection bags
using the Python value_counts under pandas bags statistical
use statistics to complete dictionary dict
Example:
a = [1, 2, 3, 1, 1, 2]
dict = {}
for key in a:
dict[key] = dict.get(key, 0) + 1
print dict
1
2
3
4
5
输出结果:
{. 1 >>>:. 3, 2: 2,. 3:}. 1
. 1
Counter in the use of collection bags Python
example:
Collections Counter Import from
A = [. 1, 2,. 3,. 1,. 1, 2]
Result = Counter (A)
Print Result
. 1
2
. 3
. 4
output:
{. 1 >>>:. 3, 2: 2,. 3:}. 1
. 1
value_counts method in the Python package pandas
Example:
PD PANDAS AS Import
A = [. 1, 2,. 3,. 1,. 1, 2]
Result = pd.value_counts (A)
Print Result
. 1
2
. 3
. 4
output:
. 3 >>> 1
2 2
. 3. 1
. 1
2
. 3
Note: use value_counts under PANDAS (), not only can count the number of each of the elements appear in the list, but also the elements of the matrix statistics.
For example:
import pandas as pd
a = pd.DataFrame([[1,2,3],
[3,1,3],
[1,2,1]])
result = a.apply(pd.value_counts)
print result
1
2
3
4
5
6
输出结果:
0 1 2
1 2.0 1.0 1.0 # 1 represents the element 2 in the first column appears in the second column 1, appears in the third column 1
2 NaN 2.0 NaN # 2 represents the elements present 0 times in the first column, appears twice in the second column, the third column appears in the zero-order
3 1.0 NaN 2.0 # 3 1 occurrence represents an element in the first column, the second column appears 0 times, appear twice in the third column
---- ------------
Disclaimer: this article is CSDN blogger original article "Scorpio Sheng Danjie", and follow CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Original link: https: //blog.csdn.net/sinat_24091225/article/details/77925473