-1

In the dataset I have columns NAME,ID, SEX, AGE, CITY where each column doesnt have any null value. The SEX column has "F" for Female and "M" for Male. Now I want to get the percentage of male and female players across the world. How can we get it. To get it across the world we can use all the values of city column. but how to get percentage of male and female.

desertnaut
  • 57,590
  • 26
  • 140
  • 166
  • 2
    Does this answer your question? [Pandas get frequency of item occurrences in a column as percentage](https://stackoverflow.com/questions/50558458/pandas-get-frequency-of-item-occurrences-in-a-column-as-percentage) – Roim May 22 '21 at 15:11

1 Answers1

-1

You can do this for all unique values in a column at once by using the value_counts function to get the count of each unique value, then divide by the count to get the percentage for each one.

import pandas as pd

data = {'Name': ['Alice', 'Bob', 'Carol'],
        'Id': [1, 2, 3],
        'Sex': ['F', 'M', 'F'],
        'Age': [30, 32, 34],
        'City': ['NY', 'LA', 'Chicago']
        }

df = pd.DataFrame(data)

pcts = df['Sex'].value_counts() / df['Sex'].count() * 100

print('% M', pcts['M'])
print('% F', pcts['F'])
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880