我有一个 Pandas 数据框,如下所示:
类型 | 地点 | 通过 | 已报名 |
---|---|---|---|
学生 | 美国 | 是的 | 高中 |
学生 | CA | 是的 | 高中 |
老师 | 美国 | 是的 | 大学 |
老师 | 美国 | 不 | 大学 |
学生 | 美国 | 不 | 高中 |
学生 | CA | 是的 | 大学 |
学生 | CA | 不 | 大学 |
我想获取通过率并按类型、位置和注册进行分组,所以它看起来像这样:
类型 | 地点 | 已报名 | 通过率 |
---|---|---|---|
学生 | 美国 | 高中 | .5 |
学生 | CA | 高中 | 1.0 |
学生 | CA | 大学 | .5 |
老师 | 美国 | 大学 | 1.0 |
创建上述数据框:
import pandas as pd
list_of_dict = [
{"type": "student", "location": "US", "pass": "yes", "enrolled": "highschool"},
{"type": "student", "location": "CA", "pass": "yes", "enrolled": "highschool"},
{"type": "teacher", "location": "US", "pass": "yes", "enrolled": "college"},
{"type": "teacher", "location": "US", "pass": "no", "enrolled": "college"},
{"type": "student", "location": "US", "pass": "no", "enrolled": "highschool"},
{"type": "student", "location": "CA", "pass": "yes", "enrolled": "college"},
{"type": "student", "location": "CA", "pass": "no", "enrolled": "college"},
]
df = pd.DataFrame(list_of_dict)
我知道我需要在按“类型”、“位置”和“已注册”分组时获取 .count()。
我已经尝试过了
df = df.groupby(["type", "location", "enrolled"]).count().mean()
但这只是给了我一个整数。
您可以将第
'Yes'
列上的 'No'
和 1
分别替换为 0
和 'pass'
,然后在其他列上替换 groupby
并得到 mean
。
df["pass"] = df["pass"].map({"yes": 1, "no": 0})
df = (
df.groupby(["type", "location", "enrolled"])["pass"]
.mean()
.reset_index(name="pass_rate")
)
type location enrolled pass_rate
0 student CA college 0.5
1 student CA highschool 1.0
2 student US highschool 0.5
3 teacher US college 0.5