python - Widening Pandas Data Frame, Similar to Pivot or Stack/Unstack -


my problem best explained example:

what have:

id0,id1,time,data0,data1  1   1   10  'a'    93  1   2   10  'a'    55  1   1   12  'a'    88  1   2   12  'b'    66  2   3   102 'c'    14  2   4   102 'a'    22  2   4   112 'd'    15  2   3   112 'b'    43 

what like:

id0,id1,time,data0,data1,data0.2,data1.2  1   1   10   'a'    93    'a'    55  1   2   10   'a'    55    'a'    93  1   1   12   'a'    88    'b'    66  1   2   12   'b'    66    'a'    88  2   3   102  'c'    14    'a'    22  2   4   102  'a'    22    'c'    14  2   4   112  'd'    15    'b'    43  2   3   112  'b'    43    'd'    15 

essentially, there 2 unique id1s associated every id0.

data sampled periodically.

i make original data frame 'wider' adding more columns each row contains information other id1 same time period.

try:

grb = df.groupby(['id0', 'time']) df['data0.2'] = grb['data0'].transform(lambda ts: ts[::-1]) df['data1.2'] = grb['data1'].transform(lambda ts: ts[::-1]) 

what doing is, based on statement that

there 2 unique id1s associated every id0.

it groups data-frame ['id0', 'time'] , reverses specific columns; if there 2 unique id1s in each group, data-frame expanded values other id1;

>>> df    id0  id1  time data0  data1 data0.2  data1.2 0    1    1    10   'a'     93     'a'       55 1    1    2    10   'a'     55     'a'       93 2    1    1    12   'a'     88     'b'       66 3    1    2    12   'b'     66     'a'       88 4    2    3   102   'c'     14     'a'       22 5    2    4   102   'a'     22     'c'       14 6    2    4   112   'd'     15     'b'       43 7    2    3   112   'b'     43     'd'       15  [8 rows x 7 columns] 

final edit: both columns together, may try below; note .values necessary in here:

>>> grb = df.groupby(['id0', 'time']) >>> df2 = grb['data0', 'data1'].transform(lambda obj: obj.values[::-1]) >>> df.join(df2, rsuffix='.2') 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -