简体   繁体   English

Pandas 数据框将行转换为列

[英]Pandas dataframe convert rows to columns

I've been trying to do this for a while and I've even checked out some other threads here but it seems like nobody's been having a problem like this until now.我已经尝试这样做了一段时间,我什至在这里查看了一些其他线程,但似乎直到现在为止没有人遇到过这样的问题。 This is my dataframe这是我的数据框

So, I've been trying to turn the "TipoPromo" column that contains 10 different possible values into 10 different columns, the values on these columns should be the ones that appear on the column "Desconto".因此,我一直在尝试将包含 10 个不同可能值的“TipoPromo”列转换为 10 个不同的列,这些列上的值应该是出现在“Desconto”列上的值。 Doing this I expect to reduce the number of rows on my dataframe significantly, and thus reducing the duplicates that you guys can see on the other rows (If you look at the columns "tickets" etc you'll see that there are many values that repeat themselves).这样做我希望显着减少我的数据帧上的行数,从而减少你们可以在其他行上看到的重复项(如果你查看“票”等列,你会看到有很多值重复自己)。 I've tried using the pivot function but without much success.我试过使用 pivot 函数,但没有太大成功。 Could you guys understand what I'm trying to say?你们能明白我想说什么吗?

Any help will be really appreciated!任何帮助将不胜感激!

pivot tables in pandas can solve this issue. pandas 中的数据透视表可以解决这个问题。 I copied the top 5 and one below the ellipsis rows as a csv file, then:我将省略号行下方的前 5 个和一个复制为 csv 文件,然后:

df=pd.read_csv('data.txt',header=0)

cols=df.columns
cols=cols.drop(['Desconto','TipoPromo'])

df.pivot_table(columns='TipoPromo' , values='Desconto', index=cols.to_list()).reset_index()

This gives:这给出:

TipoPromo           Mes        Dias Semana DiaSemana       Bandeira           Categoria  Tickets  ...  Venda Liquida          CMV  CODIGO 12   DIGITAL  MARK DOWN (CODIGO 5)  MEU DESCONTO  NIVEL LOJA
0          JANEIRO/2019  2019-01-06    S01       DOM  PAO DE ACUCAR  PEREC COMPLEMENTER   152240  ...    1956066.000  1340467.172        NaN       NaN                   NaN      26463.40         NaN
1          OUTOBRO/2021  2021-10-25    S44       SEG    EXTRA HIPER             LIQUIDA    24344  ...     453297.096   376097.323        0.0  14363.72                -21.05       1852.07    5776.574

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

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