Frequency of a single value in dataframe column
Question:
Let a column of dataset be
ITEM
2
10
-200
3
6
-200
-200
and i want to get only the number of times -200 occured in the column and also the percentage
for example in given data set we have 7 rows and out of those, 3 rows have -200 then result should be 42.8%
I tried
df['ITEM'].value_counts()
where df is data frame
and i want result to be
-200 42.8%
Answers:
You can try Series.value_counts
with normalize=True
then select the -200
row
out = (df['ITEM'].value_counts(normalize=True)
.mul(100).round(1).astype(str).add('%')
[[-200]])
$ print(out)
-200 42.9%
Name: ITEM, dtype: object
import pandas as pd
df = pd.DataFrame(data={'a':[2,10,-200,3,6,-200,-200]})
print(df["a"].value_counts(normalize=True) * 100)
# -200 42.857143
# 2 14.285714
# 10 14.285714
# 3 14.285714
# 6 14.285714
Let a column of dataset be
ITEM
2
10
-200
3
6
-200
-200
and i want to get only the number of times -200 occured in the column and also the percentage
for example in given data set we have 7 rows and out of those, 3 rows have -200 then result should be 42.8%
I tried
df['ITEM'].value_counts()
where df is data frame
and i want result to be
-200 42.8%
You can try Series.value_counts
with normalize=True
then select the -200
row
out = (df['ITEM'].value_counts(normalize=True)
.mul(100).round(1).astype(str).add('%')
[[-200]])
$ print(out)
-200 42.9%
Name: ITEM, dtype: object
import pandas as pd
df = pd.DataFrame(data={'a':[2,10,-200,3,6,-200,-200]})
print(df["a"].value_counts(normalize=True) * 100)
# -200 42.857143
# 2 14.285714
# 10 14.285714
# 3 14.285714
# 6 14.285714