Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a row of data in pandas as a dict

Tags:

python

pandas

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()
))
like image 361
David542 Avatar asked Dec 17 '18 22:12

David542


2 Answers

Try with to_dict

df.loc[1].to_dict()
like image 54
BENY Avatar answered Sep 18 '22 12:09

BENY


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}
like image 39
timgeb Avatar answered Sep 22 '22 12:09

timgeb