gpt4 book ai didi

Python行与列之间的交互

转载 作者:行者123 更新时间:2023-11-30 22:40:57 25 4
gpt4 key购买 nike

我有以下程序:

df = pd.DataFrame({
'student':['a'] * 3 + ['b'] * 3 + ['c'] * 4,
'semester':[1, 1, 2, 2, 1, 1, 2, 2, 2, 2],
'passed_exam':[True, False] * 5,
'exam': [
'French', 'English', 'Italian', 'Chinese', 'Russian',
'German', 'Chinese', 'Spanish', 'English', 'French'
]
})

print (df)

passed_exam exam semester student
0 True French 1 a
1 False English 1 a
2 True Italian 2 a
3 False Chinese 2 b
4 True Russian 1 b
5 False German 1 b
6 True Chinese 2 c
7 False Spanish 2 c
8 True English 2 c
9 False French 2 c

有人知道如何找到每个学生(通过考试)互动的学生数量吗?

类似这样的事情:

      passed_exam   exam      semester student   total_st
0 True French 1 a 1
1 False English 1 a 1
2 True Italian 2 a 1
3 False Chinese 2 b 1
4 True Russian 1 b 1
5 False German 1 b 1
6 True German 2 c 2
7 False Spanish 2 c 2
8 True English 2 c 2
9 False French 2 c 2

提前谢谢您!

最佳答案

我将“每个学生(通过考试)互动的学生数量”解释为参加同一考试的学生数量。

那么,看起来是这样的:

df1 = (df
.groupby(["exam","semester"], as_index=False)["student"].agg("count")
.rename(columns={"student":"total_st"}))
df.merge(df1).sort_values(["semester","student"])

passed_exam exam semester student total_st
0 True French 1 a 1
1 False English 1 a 1
5 True Russian 1 b 1
6 False German 1 b 1
2 True Italian 2 a 1
3 False Chinese 2 b 2
4 True Chinese 2 c 2
7 False Spanish 2 c 1
8 True English 2 c 1
9 False French 2 c 1

关于Python行与列之间的交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42734383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com