MY DF:
c1 | C2 | C3
A | B | C
A | B | N
S | B | I
I want to know how many times B
occured in column C2
.
I want that output in a list
Desired output:
mylist=[3]
One approach, which could generalize well if you later want to know how many of two or more different values appear in a field, is to use value_counts
:
df['C2'].value_counts()
Out[28]:
B 3
Name: C2, dtype: int64
df['C2'].value_counts().tolist()
Out[29]: [3]
df['C2'].value_counts().to_dict()
Out[30]: {'B ': 3}
df['c1'].value_counts()
Out[31]:
A 2
S 1
Name: c1, dtype: int64
df['c1'].value_counts().tolist()
Out[32]: [2, 1]
df['c1'].value_counts().to_dict()
Out[33]: {'A ': 2, 'S ': 1}
Edit:
To get value_counts
list output ordered based on first appearance, you could use
df['c1'].value_counts().reindex(df['c1'].unique()).tolist()
Ex:
df
Out[65]:
c1 C2 C3
0 S B C
1 A B N
2 A B I
df['c1'].value_counts().reindex(df['c1'].unique()).tolist()
Out[66]: [1, 2]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments