计算已过滤列属性的百分比

时间:2017-01-15 09:51:48

标签: python python-3.x pandas

我想计算每个社区的破水点百分比。到目前为止,我能够获得社区名单和破水点。

到目前为止,这是我的代码:

import pandas as pd

df = pd.DataFrame((data))
gb = df.groupby(['water_point_condition'])
grouped = gb[["communities_villages", "water_point_condition"]].get_group("broken")
print(grouped)

结果是:

results

这解决了我的问题,我能够获得每个社区的破水点百分比:

df = pd.DataFrame(data)
grouped = df.groupby(['water_point_condition'])
rank_by_percentage = 100 * df[df.water_point_condition == 'broken'].communities_villages.value_counts() / grouped["water_point_condition"].get_group("broken").count()
print(rank_by_percentage)

1 个答案:

答案 0 :(得分:0)

您需要按ommunities_villages分组,而不是water_point_condition

分组
df.groupby('communities_villages')['water_point_condition'].apply(lambda x: (x == 'broken').mean())