Check values between GROUP BY and a column

Viewed 110

I have a dataframe like this

 df = pd.DataFrame({'Name': ['Bob', 'Fob', 'Lob', 'Joe', 'Roe', 'Qoe'],
                'Country': [US,UK,UK,DE,US,AU],
                'Languages Known': ["Python, Java, C++","Java","Python","Python, C++","C++","Python"]})

df



Name    Country     Value   
 Bob     US          Python, Java, C++      
 Fob     UK          Java
 Lob     UK          Python
 Joe     DE          Python, C++
 Roe     US          C++
 Qoe     AU          Python

My Goal is to deduce the percentage of developers who know python in each country.

Country     Percentage   
US          50      
UK          50
DE          100
AU          100

Until now I have grouped the countries with index countries = df.groupby('Country').count().reset_index() how do I compare a group's values to other columns also need to count the no of "Python"s in a country and percentage

Thank you.

2 Answers

You can do it like this:

df_out = ((df['Languages Known'].str.split(',').explode() == "Python")
                               .sum(level=0)
                               .groupby(df['Country'])
                               .mean())
df_out

Output:

Country
AU    1.0
DE    1.0
UK    0.5
US    0.5
Name: Languages Known, dtype: float64

Another option for this use case

df['Languages Known'].str.contains('Python').groupby(df['Country']).mean()

Output:

Country
AU    1.0
DE    1.0
UK    0.5
US    0.5
Name: Languages Known, dtype: float64
Related