简体   繁体   English

转换表格格式 - 长到宽 - 两列表格 - Pandas / Excel

[英]Convert table format - long to wide - table with two columns - Pandas / Excel

I have a table like this我有一张这样的桌子

Program     Seg     Percent
N           A       1%
N           B       13%
N           C       4%
Y           A       6%
Y           B       5%
Y           C       8%

Would like to convert it to:想将其转换为:

Seg        A           A          B           B           C           C
Program    N           Y          N           Y           N           Y
Percent    1%          6%         13%         5%          4%          8%

Whether seg or program appear as title of columns or row index is not really important. seg 或 program 是否显示为列标题或行索引并不重要。 Just want it to be selectable in some way in python.只是希望它在 python 中以某种方式可选。

Note that simply transposing is not what I'm looking for.请注意,简单的转置不是我想要的。 I need to have 'Seg' as the first variable, then 'Program'.我需要将“Seg”作为第一个变量,然后是“Program”。

Looking for the solution in both Pandas and possibly Excel.在 Pandas 和可能的 Excel 中寻找解决方案。

Thanks谢谢

Create subset with expected order, sort by both columns by DataFrame.sort_values and last transpose by DataFrame.T :创建具有预期顺序的子集,按DataFrame.sort_values按两列排序,最后按DataFrame.T转置:

df = df[['Seg','Program','Percent']].sort_values(['Seg','Program']).T
print (df)
          0   3    1   4   2   5
Seg       A   A    B   B   C   C
Program   N   Y    N   Y   N   Y
Percent  1%  6%  13%  5%  4%  8%

Solution with MulitIndex (repeated values are not displayed only):使用MulitIndex的解决方案(不只显示重复值):

df = df.set_index(['Seg','Program'])[['Percent']].sort_index().T
print (df)
Seg       A        B       C    
Program   N   Y    N   Y   N   Y
Percent  1%  6%  13%  5%  4%  8%

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

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