'Python pivot table: add a common date column for each group
I am making a pivot table where cell values are test results, indexes are users and columns are test types. Each user done several sets of tests (three different tests per set), every set has own date.
*My question is following: how to add a columns "Date" to each test set (since items in one set have same date), i.e. date when was done first set, second set etc. Desired output is below *
I tried to use .map() method in order to match date with combined index of user id and set number, but failed. Because columns have several layers, it seems quite complicated for me, so I would be really greatful for any suggestions. Thank you !
df = pd.DataFrame({'User': ['A1', 'A1', 'A1', 'A1', 'A1', 'A1',
'A2', 'A2', 'A2', 'A2', 'A2', 'A2',
'A3', 'A3', 'A3'],
'Time': ['2010-01-15', '2010-01-15', '2010-01-15', '2010-01-17', '2010-01-17', '2010-01-17',
'2012-12-10', '2012-12-10', '2012-12-10', '2012-12-15', '2012-12-15', '2012-12-15',
'2013-03-05', '2013-03-05', '2013-03-05'],
'Test_Type': ['Type1', 'Type2', 'Type3', 'Type1', 'Type2', 'Type3',
'Type1', 'Type2', 'Type3', 'Type1', 'Type2', 'Type3',
'Type1', 'Type2', 'Type3'],
'Test_Result': ['T', 'F', 'F', 'F', 'F', 'F',
'T', 'T', 'T', 'F', 'F', 'F',
'T', 'F', 'F'],
'Test_Set_No': ['1', '1', '1', '2', '2', '2',
'1', '1', '1', '2', '2', '2',
'1', '1', '1']})
Output:
My current pivot function is:
pd.pivot_table(df, values=['Test_Result'],
index=['User'],
columns=['Test_Set_No', 'Test_Type'],
fill_value=np.nan, aggfunc='first')
Current pivot output:
Desired pivot output:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
