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()
))
Try with to_dict
df.loc[1].to_dict()
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With