Home > Blockchain >  Divide dataframe into list of rows containing all columns
Divide dataframe into list of rows containing all columns

Time:07-21

From dataframe sructured like this

A B
1 2
3 4

I need to get list like this:

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

CodePudding user response:

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'}]
  • Related