Home > database >  Pandas: duplicate keys and transpose matrix in dictionary type
Pandas: duplicate keys and transpose matrix in dictionary type

Time:09-21

I have a dict data 'df':

df = {'index': [27, 28, 29, 30, 31],
'data': [[1, 2, 3, 4, 5, 6, 7],
[8, 9, 10, 11, 12, 13, 14],
[15, 16, 17, 18, 19, 20, 21],
[22, 23, 24, 25, 26, 27, 28],
[29, 30, 31, 32, 33, 34, 35]]}

I want to change 'data' key to the equivalent transpose matrix, and I want to duplicate the 'index' key as many times as there are columns in the resulted 'data' key (5 times in this case) :

df = {'index': [27, 28, 29, 30, 31], [27, 28, 29, 30, 31], [27, 28, 29, 30, 31], [27, 28, 29, 30, 31], [27, 28, 29, 30, 31],
'data': [[1, 8, 15, 22, 29],
[2, 9, 16, 23, 30],
[3, 10, 17, 24, 31],
[4, 11, 18, 25, 32],
[5, 12, 19, 26, 33],
[6, 13, 20, 27, 34],
[7, 14, 21, 28, 35]]}

How can I proceed? Thanks.

CodePudding user response:

df = {'index': [df['index']]*np.array(df['data']).T.shape[1],
      'data':df['index']*np.array(df['data']).T}

Transpose data after converting to numpy array, tile the index by a factor inferred from transposed array's shape.

CodePudding user response:

You can transpose with zip

df = {'index': [27, 28, 29, 30, 31],
'data': [[1, 2, 3, 4, 5, 6, 7],
[8, 9, 10, 11, 12, 13, 14],
[15, 16, 17, 18, 19, 20, 21],
[22, 23, 24, 25, 26, 27, 28],
[29, 30, 31, 32, 33, 34, 35]]}

df_new = {}
df_new['index'] = [df['index']]* len(df['data'])
df_new['data'] = list(zip(*df['data']))

print(df_new)

CodePudding user response:

Try from_records

out = pd.DataFrame.from_records(data=df['data'],index=df['index'])
Out[191]: 
     0   1   2   3   4   5   6
27   1   2   3   4   5   6   7
28   8   9  10  11  12  13  14
29  15  16  17  18  19  20  21
30  22  23  24  25  26  27  28
31  29  30  31  32  33  34  35
  • Related