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()
))
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}
df.loc[x] returns a mapping, a pd.Series, so you can just use the dict constructor directly:
dict(df.loc[100])
Or the to_dict helper method if you prefer...
This sort of raises the question, are you sure you need a dict at all?
You can use: df.to_dict('records')
Ref: pandas docs.
Say you have a df:
>>> df
Out[1]:
alpha beta ... log_10_rate rate
0 2.530809 3.446069 ... 1.299609 19.934677
1 1.418243 1.861504 ... 1.059239 11.461440
... ... ... ... ... ...
11241 2.462758 -0.890800 ... 1.532919 34.112962
11242 2.462758 -0.890800 ... 1.437005 27.353010
[11243 rows x 21 columns]
To get the ith row as a dict, I would do:
df.to_dict('records')[11242]
Out[2]:
{'alpha': 2.462758375498395,
'beta': -0.8908002057212157,
'mmax': 90.14711749088858,
...
}
Say your dataframe is df and you want the row with index k, you can do:
list(df.iloc[k,:])
The result will be a list of all the values in row k.