首页 > 解决方案 > 阻止熊猫重命名具有相同名称的列,以便我可以使用宽到长

问题描述

我有一个 excel 文件,我正在读入看起来与此类似的 pandas

name        size    color   material        size    color   material    size    color   material
bob         m       red     coton           m         yellow  cotton      m         green   dri-fit
james       l       green   dri-fit         l         green   cotton      l         red     cotton
steve       l       green   dri-fit         l         green   cotton      l         red     cotton

我想把我所有的衬衫类型都统计成这样

l green dri-fit   2
l red   coton     2
m red   coton     1

我正在使用 pandas ExcelFile 将文件读入文件对象,然后使用 parse 将工作表解析为数据框。

import pandas as pd
file = pd.ExcelFile('myexcelfile.xlsx')
df = file.parse('sheet1')

为了尝试获得我想要的输出,我尝试使用 Wide to Long。问题是,因为我的某些列具有相同的名称,所以当我将文件读入 pandas 时,它会重命名我的列。例如,第二个 size 实例会自动变成 size.2,与颜色和材质相同。如果我尝试使用从宽到长的存根名称,它会抱怨大小的第一个实例......“存根名称不能与列名相同”。

在熊猫重命名我的列之前,有什么方法可以使用宽到长吗?

标签: pandas

解决方案


的列编号是有问题的pd.wide_to_long,所以我们需要修改列名的第一个实例,添加一个.0,这样它们就不会与存根冲突。

样本数据

import pandas as pd
df = pd.read_clipboard() 
print(df)

    name size  color material size.1 color.1 material.1 size.2 color.2 material.2
0    bob    m    red    coton      m  yellow     cotton      m   green    dri-fit
1  james    l  green  dri-fit      l   green     cotton      l     red     cotton
2  steve    l  green  dri-fit      l   green     cotton      l     red     cotton

代码:

stubs = ['size', 'color', 'material']
d = {x: f'{x}.0' for x in stubs}
df.columns = [d.get(k, k) for k in df.columns]

res = pd.wide_to_long(df, i='name', j='num', sep='.', stubnames=stubs)
#          size   color material
#name  num                      
#bob   0      m     red    coton
#james 0      l   green  dri-fit
#steve 0      l   green  dri-fit
#bob   1      m  yellow   cotton
#james 1      l   green   cotton
#steve 1      l   green   cotton
#bob   2      m   green  dri-fit
#james 2      l     red   cotton
#steve 2      l     red   cotton

res.groupby([*res]).size()
#size  color   material
#l     green   cotton      2
#              dri-fit     2
#      red     cotton      2
#m     green   dri-fit     1
#      red     coton       1
#      yellow  cotton      1

推荐阅读