简体   繁体   English

Pandas 数据框转换

[英]Pandas Dataframe transformations

I am new to python and have a need where I need to trasform below pandas dataframe -我是python的新手,需要在pandas数据框下方进行转换 -

type           c1                 c2             c3
 a             9                  10.0          -11.11
 b             162                165.0         -1.85
 c             16                 15.0           6.25

to this format-到这种格式-

      a                  b                 c
c1   c2    c3      c1    c2    c3    c1   c2   c3
9   10.0 -11.11    162  165 -1.85    16  15.0  6.25

I have tried various combinations of transpose, multi-indexing and pivoting but no luck, could you please help me find the solution for this.我尝试了转置、多索引和旋转的各种组合,但没有成功,请您帮我找到解决方案。

Thanks!谢谢!

Here's one way:这是一种方法:

df1 = df.set_index('type').stack()
df = pd.DataFrame(df1.values.reshape(-1,len(df1)), columns = df1.index)

Alternative:选择:

df = df.set_index('type').stack().to_frame().T

OUTPUT:输出:

type    a                   b                  c            
       c1    c2     c3     c1     c2    c3    c1    c2    c3
0     9.0  10.0 -11.11  162.0  165.0 -1.85  16.0  15.0  6.25

Try this:试试这个:

result = (
    df.set_index('type')
      .stack()
      .to_frame()
      .T
)

If you feel overwhelmed by the chain of operations, try one line a time to see its effect:如果您对操作链感到不知所措,请一次尝试一行以查看其效果:

Step 1:步骤1:

(
    df.set_index('type')
      .stack()
    # .to_frame()
    # .T
)

Step 2:第2步:

(
    df.set_index('type')
      .stack()
      .to_frame()
    # .T
)

And so on...等等...

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

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