Python:一次包含重复值的多个列的 Pandas 数据透视表

2023-10-19Python开发问题
5

本文介绍了Python:一次包含重复值的多个列的 Pandas 数据透视表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

有一个包含名称、学校和标记列的 pandas 数据框

have a pandas dataframme with columns name , school and marks

name  school  marks

tom     HBS     55
tom     HBS     55
tom     HBS     14
mark    HBS     28
mark    HBS     19
lewis   HBS     88

如何转置和转换成这样的

How to transpose and convert into like this

name  school  marks_1 marks_2 marks_3

tom     HBS     55     55       14
mark    HBS     28     19
lewis   HBS     88

试过这个:

df = df.pivot_table(index='name', values='marks', columns='school') 
    .reset_index() 
    .rename_axis(None, axis=1)

print(df)

df = df.pivot('name','marks','school')

检查了这些链接

https://stackoverflow.com/questions/22798934/pandas-long-to-wide-reshape-by-two-variables
https://stackoverflow.com/questions/62391419/pandas-group-by-and-convert-rows-into-multiple-columns
https://stackoverflow.com/questions/60698109/pandas-multiple-rows-to-single-row-with-multiple-columns-on-2-indexes

由于重复值而出现此错误.如果存在重复如何处理,我们必须保留它们

getting this error due to duplicate values. how to handle if duplicate exists and we have to keep them

ValueError: Index contains duplicate entries, cannot reshape

推荐答案

尝试使用 set_indexunstackgroupbycumcount:

Try using set_index and unstack with groupby and cumcount:

df_out = df.set_index(['name',
                       'school',
                       df.groupby(['name','school'])
           .cumcount() +1]).unstack()
df_out.columns = [f'{i}_{j}' for i, j in df_out.columns]
df_out = df_out.reset_index()
df_out

输出:

    name school  marks_1  marks_2  marks_3
0  lewis    HBS     88.0      NaN      NaN
1   mark    HBS     28.0     19.0      NaN
2    tom    HBS     55.0     55.0     14.0

这篇关于Python:一次包含重复值的多个列的 Pandas 数据透视表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10