Get a row of data in pandas as a dict

  • A+
Category:Languages

To get a row of data in pandas by index I can do:

df.loc[100].tolist() 

Is there a way to get that row of data as a dict, other than doing:

dict(zip(     df.columns.tolist(),     df.loc[100], tolist() )) 

 


You will run into a problem if you have columns with non-unique names.

Demo:

>>> df = pd.DataFrame([[1,2,3,4,5], [6,7,8,9,10]], columns=['A', 'B', 'A', 'C', 'B'])                                      >>> df                                                                                                                     A  B  A  C   B 0  1  2  3  4   5 1  6  7  8  9  10 >>> df.loc[1].to_dict()                                                                                                 {'A': 8, 'B': 10, 'C': 9} 

If this can happen in your dataframe, make the columns unique before creating the dict.

Here's an idea to do so:

>>> from itertools import count  >>>                                                                                        >>> col_isdupe = zip(df.columns, df.columns.duplicated(keep=False))                                                     >>> counters = {c:count() for c, dupe in col_isdupe if dupe}                                                            >>> df.columns = ['{}_{}'.format(c, next(counters[c])) if c in counters else c  ...:              for c in df.columns]                                >>> df                                                                                                                     A_0  B_0  A_1  C  B_1 0    1    2    3  4    5 1    6    7    8  9   10 >>>                                                                                                                     >>> df.loc[1].to_dict()                                                                                                 {'A_0': 6, 'A_1': 8, 'B_0': 7, 'B_1': 10, 'C': 9} 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: