以字典的形式获取pandas中的一行数据 [英] Get a row of data in pandas as a dict

查看:95
本文介绍了以字典的形式获取pandas中的一行数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要通过索引获取pandas中的一行数据,我可以这样做:

df.loc[100].tolist()

有没有办法将那行数据作为字典获取,而不是这样做:

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

解决方案

如果列的名称不唯一,您将遇到问题.

演示:

<预><代码>>>>df = pd.DataFrame([[1,2,3,4,5], [6,7,8,9,10]], columns=['A', 'B', 'A', 'C', 'B'])>>>dfA B A C B0 1 2 3 4 51 6 7 8 9 10>>>df.loc[1].to_dict(){'A':8,'B':10,'C':9}

如果这可能发生在您的数据框中,请在创建字典之前使列唯一.

这是一个这样做的想法:

<预><代码>>>>从 itertools 导入计数>>>>>>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...:对于 df.columns 中的 c]>>>dfA_0 B_0 A_1 C B_10 1 2 3 4 51 6 7 8 9 10>>>>>>df.loc[1].to_dict(){'A_0':6,'A_1':8,'B_0':7,'B_1':10,'C':9}

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}

这篇关于以字典的形式获取pandas中的一行数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆