Skip to content
Advertisement

Divide dataframe into list of rows containing all columns

From dataframe sructured like this

   A B
 0 1 2
 1 3 4

I need to get list like this:

[{"A": 1, "B": 2}, {"A": 3, "B": 4}]

Advertisement

Answer

It looks like you want:

df.values.tolist()

example:

df = pd.DataFrame([['A', 'B', 'C'],
                   ['D', 'E', 'F']])

df.values.tolist()

output:

[['A', 'B', 'C'],
 ['D', 'E', 'F']]

other options

df.T.to_dict('list')
{0: ['A', 'B', 'C'],
 1: ['D', 'E', 'F']}

df.to_dict('records')
[{0: 'A', 1: 'B', 2: 'C'},
 {0: 'D', 1: 'E', 2: 'F'}]
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement