【问题标题】:How to transpose row and columns using pandas?如何使用熊猫转置行和列?
【发布时间】:2019-12-27 09:53:01
【问题描述】:

我是 pandas 的新手,我得到的结果与我的预期结果相反。

我试过的是:

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")

我得到的输出是:

             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

我真正想要的是:

                    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=[]

如何得到实际输出?

【问题讨论】:

标签: python python-3.x pandas rows


【解决方案1】:

您可以使用不带转置的concataxis=1 简化您的解决方案,重命名索引值,然后通过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

如果需要创建不重复第一级MultiIndex(不推荐)的文件,请使用answer

【讨论】:

  • 感谢您的代码。如何按 'RED' 、 'GREEN' 顺序获取列?
  • @itsbinz - 使用df1 = df1[['RED','GREEN']]
  • 如何从列表中命名索引,列表可能包含 [A1,A3,A8],而不是按顺序排列
  • @itsbinz - 删除 .rename(lambda x: f'A{x+1}')) 并使用 pop_complete.index = [A1,A3,A8]
  • @itsbinz - 你是对的,在最后一行代码中添加了.reindex(["O", "A", "O-A"], axis=0, level=1)
猜你喜欢
  • 2022-06-14
  • 1970-01-01
  • 2018-12-06
  • 1970-01-01
  • 2020-03-23
  • 2022-12-18
  • 2012-08-19
  • 2019-12-31
  • 1970-01-01
相关资源
最近更新 更多