I have a Dataframe as
JavaScript
x
7
1
import pandas as pd
2
df = pd.DataFrame({
3
"First": ['First1', 'First2', 'First3'],
4
"Secnd": ['Secnd1', 'Secnd2', 'Secnd3']
5
)
6
df.index = ['Row1', 'Row2', 'Row3']
7
I would like to have a lambda
function in apply
method to create a list of dictionary (including index item) as below
JavaScript
1
6
1
[
2
{'Row1': ['First1', 'Secnd1']},
3
{'Row2': ['First2', 'Secnd2']},
4
{'Row3': ['First3', 'Secnd3']},
5
]
6
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:
JavaScript
1
2
1
[{k: list(v.values())} for k, v in df.to_dict('index').items()]
2