0

I have dataframe something like this

| ID   | M001 | M002 | M003 | M004 |
|------|------|------|------|------|
| E001 | 3    | 4    | 3    | 2    |
| E002 | 4    | 5    | 5    | 3    |
| E003 | 4    | 3    | 5    | 4    |

And I want output in list but something like this for each unique ID such E001, E002 i want list of their response in each M001, M002 and so on

My required output is different variable for different id lets say E001_response = [["M001",3],["M002",4],["M003",3],["M004",2]]

rpanai
  • 12,515
  • 2
  • 42
  • 64
  • 1
    Out of curiousity, why would you want to do this? – Erfan Dec 30 '19 at 12:58
  • @Erfan, Because I want to create report in pdf format which would contain table having each unique Id score. So for different Unique i would have different pdf file. –  Dec 30 '19 at 13:05
  • 2
    @Maqsud if that's the case - would not just iterating over the rows of the DF be convenient? eg: `for row in df.itertuples(index=False): ...` then just using `row.ID` maybe as the PDF filename and then when writing content to that access `row.M001` or `row.M004` as appropriate? – Jon Clements Dec 30 '19 at 13:21

2 Answers2

0

Something like that:

new_df = df.apply(lambda x: list(zip(df.columns, x)), axis=1)

Output:

ID
E001    [(M001, 3), (M001, 4), (M001, 3), (M001, 2)]
E002    [(M002, 4), (M002, 5), (M002, 5), (M002, 3)]
E003    [(M003, 4), (M003, 3), (M003, 5), (M003, 4)]
dtype: object
fsl
  • 3,250
  • 1
  • 10
  • 20
0

You can create Series with lists with custom lambda function:

s = df.set_index('ID').apply(lambda x: list(map(list,zip(df.columns[1:], x))), 1)
print (s)
ID
E001    [[M001, 3], [M002, 4], [M003, 3], [M004, 2]]
E002    [[M001, 4], [M002, 5], [M003, 5], [M004, 3]]
E003    [[M001, 4], [M002, 3], [M003, 5], [M004, 4]]
dtype: object

And then is possible use globals, but better is not create varables by names

for k, v in s.items():
     globals()[f'{k}_response'] = v

print (E001_response)
[['M001', 3], ['M002', 4], ['M003', 3], ['M004', 2]]

Better is create dictionary:

d = s.to_dict()
print (d)
{'E001': [['M001', 3], ['M002', 4], ['M003', 3], ['M004', 2]],
 'E002': [['M001', 4], ['M002', 5], ['M003', 5], ['M004', 3]], 
 'E003': [['M001', 4], ['M002', 3], ['M003', 5], ['M004', 4]]}

print (d['E001'])
[['M001', 3], ['M002', 4], ['M003', 3], ['M004', 2]]
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252