简体   繁体   English

如何使用pandas转置行和列?

[英]How to transpose row and columns using pandas?

I am new to pandas, I am getting a result in reverse order of my expected result. 我是熊猫的新手,我得到的结果与我预期的结果相反。

What I have tried is: 我试过的是:

o_rg,o_gg,a_rg,a_gg are arrays o_rg,o_gg,a_rg,a_gg是数组

    df1=pd.DataFrame({'RED':o_rg,'GREEN':o_gg})
df2=pd.DataFrame({'RED':a_rg,'RED':a_gg})
df=df1-(df2)
print(df)
pop_complete = pd.concat([df.T,
                          df1.T,
                          df2.T],
                          keys=["O-A", "O", "A"])
df = pop_complete.swaplevel()
df.sort_index(inplace=True)

print(df)
df.to_csv("OUT.CSV")

What I get the output as: 我得到的输出为:

             0      1       2
RED        A        14.0    12.0    15.0
           O        14.0    12.0    15.0
           O-A      0.00    0.00    0.00
GREEN      A        12.0    10.0    12.0
           O        14.0    9.0     12.0
           O-A      -2.0    1.0     0.0

What I actually want is: 我真正想要的是:

                    RED     GREEN       

        A1 O        14.0     14.0
           A        14.0     12.0
           O-A      0.0      2.0

        A3 O        12.0     9.0
           A        12.0     10.0
           O-A      0.0      -1.0

        A8 O        15.0     12.0
           A        15.0     12.0
           O-A      0.0      0.0

 where 'A1','A3','A8' ... can be stored in array cases=[]

How to get the actual output? 如何获得实际输出?

You can simplify your solution with concat without transpose and axis=1 , rename index values and then reshape by DataFrame.stack : 您可以使用concat简化解决方案而不使用转置和axis=1 ,重命名索引值,然后通过DataFrame.stack重新DataFrame.stack

o_rg = [14,12,15]
o_gg = [14,9,12]

a_rg = [14,12,15] 
a_gg = [14,10,15]

df1=pd.DataFrame({'RED':o_rg,'GREEN':o_gg})
df2=pd.DataFrame({'RED':a_rg,'GREEN':a_gg})
df=df1-(df2)
print(df)
   RED  GREEN
0    0      0
1    0     -1
2    0     -3

pop_complete = pd.concat([df, df1, df2], keys=["O-A", "O", "A"], axis=1)
pop_complete.index = ['A1','A3','A8']
print(pop_complete)
   O-A         O         A      
   RED GREEN RED GREEN RED GREEN
A1   0     0  14    14  14    14
A3   0    -1  12     9  12    10
A8   0    -3  15    12  15    15

df1 = pop_complete.stack(0)[['RED','GREEN']].reindex(["O", "A", "O-A"], axis=0, level=1)
print (df1)
        RED  GREEN
A1 O     14     14
   A     14     14
   O-A    0      0
A3 O     12      9
   A     12     10
   O-A    0     -1
A8 O     15     12
   A     15     15
   O-A    0     -3

If need create file with no repeating first level of MultiIndex (not recommended) use this answer . 如果需要创建文件而不重复第一级MultiIndex (不推荐),请使用此答案

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

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