gpt4 book ai didi

python - 以 csv 格式显示 Pandas DataFrame

转载 作者:行者123 更新时间:2023-12-01 03:40:58 25 4
gpt4 key购买 nike

我有一个 pandas 数据框 q2 ,如下所示:

    StudentID     Subjects
6 323 History
9 323 Physics
8 999 Chemistry
7 999 History
4 999 Physics
0 1234 Chemistry
5 2834 Physics
1 3455 Chemistry
2 3455 History
10 3455 Mathematics
3 56767 Mathematics

我想找出哪个学生选修了哪些类(class)并将其显示在屏幕上。

gb = q2.groupby(('StudentID'))
result = gb['Subjects'].unique()

c1=pd.DataFrame({'StudentID':result.index, 'Subjects':result.values})

c1 看起来像这样

   StudentID                           Subjects
0 323 [History, Physics]
1 999 [Chemistry, History, Physics]
2 1234 [Chemistry]
3 2834 [Physics]
4 3455 [Chemistry, History, Mathematics]
5 56767 [Mathematics]

但是,所需的输出如下:

323: History, Physics
999: Chemistry, History, Physics
1234: Chemistry
2834: Physics
3455: Chemistry, History, Mathematics
56767: Mathematics

我能做什么?

最佳答案

我想你可以apply函数加入。另外,为了创建DataFrame,您可以使用 reset_index :

gb = q2.groupby(('StudentID'))
result = gb['Subjects'].unique()

c1 = result.reset_index()

c1.Subjects = c1.Subjects.apply(', '.join)
print (c1)
StudentID Subjects
0 323 History, Physics
1 999 Chemistry, History, Physics
2 1234 Chemistry
3 2834 Physics
4 3455 Chemistry, History, Mathematics
5 56767 Mathematics

最后,您可以将列 StudentID 转换为 str (如果 dtypeint)并连接在一起:

c1['new'] = c1.StudentID.astype(str) + ':' + c1.Subjects
print (c1)
StudentID Subjects \
0 323 History, Physics
1 999 Chemistry, History, Physics
2 1234 Chemistry
3 2834 Physics
4 3455 Chemistry, History, Mathematics
5 56767 Mathematics

new
0 323:History, Physics
1 999:Chemistry, History, Physics
2 1234:Chemistry
3 2834:Physics
4 3455:Chemistry, History, Mathematics
5 56767:Mathematics

此外,如果可以覆盖原始数据,请使用:

result = result.index.to_series().astype(str) + ':' + result.apply(', '.join)
print (result)
StudentID
323 323:History, Physics
999 999:Chemistry, History, Physics
1234 1234:Chemistry
2834 2834:Physics
3455 3455:Chemistry, History, Mathematics
56767 56767:Mathematics
dtype: object

关于python - 以 csv 格式显示 Pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39645404/

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