简体   繁体   English

Python pandas: pivot DataFrame 列

[英]Python pandas: pivot DataFrame columns in rows

I have a pandas DataFrame as following, showing the scores of students in multiple subjects:我有一个 pandas DataFrame 如下,显示学生在多个科目的成绩:

       Name    Subject    Score
0       Tom          A       91
1       Tom          B       92
2       Tom          C       93
3       Bob          A       94
4       Bob          C       95
5       Ali          B       96
6       Ali          C       97

Note that not every student has scores in all subjects.请注意,并非每个学生在所有科目中都有分数。 I want to pivot it into a DataFrame like this:我想将 pivot 变成这样的 DataFrame :

      Name     A     B     C
0      Tom    91    92    93
1      Bob    94          95    
2      Ali          96    97

The goals to achieve in this pivot:在此 pivot 中要实现的目标:

  1. group the scores by 'Name'按“名称”对分数进行分组
  2. insert columns of subjects插入主题列
  3. arrange the scores at the crossing space of Name and subjects在姓名和科目的交叉空间排列分数

I'm new to pandas but I looked into DataFrame.pivot_table(), while unfortunately couldn't figure out the right way.我是 pandas 的新手,但我查看了 DataFrame.pivot_table(),但不幸的是找不到正确的方法。

You were right on with using a pivot_table to solve this:您正确地使用了pivot_table来解决这个问题:

df = df.pivot_table(index='Name', values='Score', columns='Subject') \
    .reset_index() \
    .rename_axis(None, axis=1)
print(df)

Output: Output:

  Name     A     B     C
0  Ali   NaN  96.0  97.0
1  Bob  94.0   NaN  95.0
2  Tom  91.0  92.0  93.0

Pivot also works in this case: Pivot也适用于这种情况:

df = df.pivot(index='Name', values='Score', columns='Subject') \
    .reset_index() \
    .rename_axis(None, axis=1)

Here is the solution这是解决方案

import pandas as pd
df= DATAFRAME [ as yours]
df1=df.pivot(index='Name',columns = 'Subject', values = 'Score').fillna('').round(decimals=0).astype(object)

Output Output 在此处输入图像描述

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

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