从 pandas 数据帧高效创建循环字典

Efficient dictionary creation from pandas dataframe for looping

我有以下数据框:

V1 = ['a','a','c','d']
V2 = ['test1', 'test2'  , 'test3'  , 'test4' ]
        
df = pd.DataFrame({'V1':V1,'V2':V2})
print(df.head())

V1     V2
a    test1 
a    test2
c    test3 
d    test4

我想按如下方式循环:

for [unique element in v1 column]:
    for [corresponding elements in V2]:

我考虑过用以下格式构建字典:

    dic = { 'a':['test1', 'test2'], 'c':['test3'] , 'd':['test4'] }

for elt in dic:
    for i in dic[elt]:

是否有更好的way/more有效方法来做到这一点?如果不是,我如何有效地构建这样的字典?

非常感谢您的帮助!

使用 pandas 构建字典的选项是:

dic = pd.Series(V2, index=V1).groupby(level=0).agg(list).to_dict()

输出:{'a': ['test1', 'test2'], 'c': ['test3'], 'd': ['test4']}

使用经典python,使用collections.defaultdict

from collections import defaultdict
dic = defaultdict(list)
for k,v in zip(V1, V2):
    dic[k].append(v)
    
dict(dic)
# {'a': ['test1', 'test2'], 'c': ['test3'], 'd': ['test4']}

从初始数据帧循环你的值:

df = pd.DataFrame({'V1':V1,'V2':V2})

for name, d in df.groupby('V1'):
    print(f'entering group {name}')
    for value in d['V2']:
        print(f' value {value}')

输出:

entering group a
 value test1
 value test2
entering group c
 value test3
entering group d
 value test4

您可以通过 GroupBy.agg and then Series convert to dictionary by DataFrame.to_dict 聚合 list:

 #your DataFrame
 df = pd.DataFrame({'V1':V1,'V2':V2})

 d = df.groupby('V1')['V2'].agg(list).to_dict()

只用python,不用pandas!下面的代码只需要 O(n) 时间,所以这非常快。

from collections import defaultdict

V1 = ['a','a','c','d']
V2 = ['test1', 'test2'  , 'test3'  , 'test4' ]

my_dict = defaultdict(list)

for x, y in zip(V1, V2):
    my_dict[x].append(y)

print(my_dict)

输出

defaultdict(<class 'list'>, {'a': ['test1', 'test2'], 'c': ['test3'], 'd': ['test4']})

如果您认为自己拥有非常大的数据集,则可以使用其他 pandas group by 解决方案,否则像上面这样简单高效的解决方案就足以满足一般用例。