I have a Dataframe as
import pandas as pd df = pd.DataFrame({ "First": ['First1', 'First2', 'First3'], "Secnd": ['Secnd1', 'Secnd2', 'Secnd3'] ) df.index = ['Row1', 'Row2', 'Row3']
I would like to have a lambda
function in apply
method to create a list of dictionary (including index item) as below
[ {'Row1': ['First1', 'Secnd1']}, {'Row2': ['First2', 'Secnd2']}, {'Row3': ['First3', 'Secnd3']}, ]
If I use something like .apply(lambda x: <some operation>)
here, x
does not include the index rather the values.
Cheers, DD
Advertisement
Answer
To expand Hans Bambel’s answer to get the exact desired output:
[{k: list(v.values())} for k, v in df.to_dict('index').items()]