Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve order of rows when converting pandas Dataframe to dictionary

Tags:

python

pandas

I am converting a pandas dataframe 'df' to dictionary using the command

df.to_dict( 'records')

Does this operation preserve the order of rows?

like image 686
Pulkit Bansal Avatar asked Aug 17 '17 05:08

Pulkit Bansal


1 Answers

Yes, they do. Here are two dataframes:

DataFrame 1

    Cat Vec
0   a   [1, 2, 3]
1   a   [4, 5, 6]
2   b   [1, 2, 3]

Output:

[{'Cat': 'a', 'Vec': [1, 2, 3]},
 {'Cat': 'a', 'Vec': [4, 5, 6]},
 {'Cat': 'b', 'Vec': [1, 2, 3]}]

DataFrame 2

    Cat Vec
0   a   [1, 2, 3]
1   b   [4, 5, 6]
2   a   [1, 2, 3]

Output:

[{'Cat': 'a', 'Vec': [1, 2, 3]},
 {'Cat': 'b', 'Vec': [4, 5, 6]},
 {'Cat': 'a', 'Vec': [1, 2, 3]}]
like image 199
Cory Madden Avatar answered Nov 18 '22 12:11

Cory Madden