Панды: транспонировать столбцы (b, c, d), сгруппированные по столбцу a в качестве индекса - PullRequest
0 голосов
/ 07 октября 2019

У меня есть фрейм данных:

import pandas as pd 
import numpy as np 
data = pd.DataFrame({'file':['file1','file1','file1','file2','file2','file2' ], 'x': [1,2,3,1,2,4], 'y': [10,20,30,10, 20, 40], 'norm_y': [2,4,6,2,4,8]})

print (data)

out: 
    file  x   y  norm_y
0  file1  1  10       2
1  file1  2  20       4
2  file1  3  30       6
3  file2  1  10       2
4  file2  2  20       4
5  file2  4  40       8

Я хочу напечатать его так, чтобы:

  • файл был основным индексом
  • x, y, zэто субиндекс

, чтобы он выглядел так:

    file          
0         x     1  2  3
1  file1  y     10 20 30
2         ynorm 2  4  6
3         x     1  2  4
4  file2  y     10 20 40
5         ynorm 2  4  8

Я думаю, что ответ будет примерно таким:

  • setиндекс строки: data.set_index (['file'])
  • транспонировать столбцы x, y, ynorm

Ответы [ 5 ]

3 голосов
/ 07 октября 2019

вам просто нужно немного воображения:

data.set_index('file').groupby(level=0).apply(lambda x: x.T)

Вывод:

file          file2  file2  file2
file                             
file1 x           1      2      3
      y          10     20     30
      norm_y      2      4      6
file2 x           1      2      4
      y          10     20     40
      norm_y      2      4      8
3 голосов
/ 07 октября 2019

По своей сути это проблема pivot, но не совсем простая.


df.assign(
  key=df.groupby('file').cumcount()).set_index(['file', 'key']).stack().unstack('key')

key            0   1   2
file
file1 x        1   2   3
      y       10  20  30
      norm_y   2   4   6
file2 x        1   2   4
      y       10  20  40
      norm_y   2   4   8
2 голосов
/ 07 октября 2019

Вы можете сделать:

df['col' ] = df.groupby('file').cumcount()+1
df.pivot_table(index='file', columns='col').stack(level=0)

Вывод:

col            1   2   3
file                    
file1 norm_y   2   4   6
      x        1   2   3
      y       10  20  30
file2 norm_y   2   4   8
      x        1   2   4
      y       10  20  40
1 голос
/ 07 октября 2019

Игра с numpy изменяет форму

fil, var, val = df.melt('file').values.T

new = pd.DataFrame(np.hstack([fil.reshape(-1,3)[:, 0].reshape(-1,1), 
                              var.reshape(-1,3)[:, 0].reshape(-1,1), 
                              val.reshape(-1,3)]))\
        .set_index([0,1])\
        .sort_index()

               2   3   4
0     1                 
file1 norm_y   2   4   6
      x        1   2   3
      y       10  20  30
file2 norm_y   2   4   8
      x        1   2   4
      y       10  20  40
0 голосов
/ 07 октября 2019

Попробуйте это.

(
    pd.melt(data, id_vars='file', value_vars=['x', 'y', 'norm_y']) #Unstacks the data
    .groupby(['file', 'variable'])['value'] #restacks with file and variable as index
    .aggregate(lambda x: tuple(x)) #splits out values in to a column
    .apply(pd.Series) #turns them into separate columns
)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...