繁体   English   中英

检查 GROUP BY 和列之间的值

[英]Check values between GROUP BY and a column

我有一个这样的数据框

 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

我的目标是推算出每个国家/地区了解 Python 的开发人员的百分比。

Country     Percentage   
US          50      
UK          50
DE          100
AU          100

到目前为止,我已经将国家与索引国家分组为 df.groupby('Country').count().reset_index() 如何将组的值与其他列进行比较还需要计算“Python”的数量国家和百分比

谢谢你。

你可以这样做:

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

输出:

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

此用例的另一种选择

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

输出:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM