如何获得一个字典,其中键等于dataframe中的组成员,值等于组id?

2024-06-23 18:25:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有如下数据帧:

       City     Name
0   Seattle    Alice
1   Seattle      Bob
2  Portland  Mallory       
3  Portland      Bob

我用过数据框groupby(‘城市’)对于上面的例子,我们将有2个组,即1)西雅图2)波特兰。现在我想得到一个字典,其中键是名称,值是组ID,即:

dict = {'Alice': {'1'}, 'Bob': {'1','2'}, 'Mallory': {'2'}}

什么是有效的方法?你知道吗


Tags: 数据方法name名称idcity字典dict
1条回答
网友
1楼 · 发布于 2024-06-23 18:25:53

此代码将为您提供一个列表,作为字典中每个名称的条目:

    array = df.data
    names = array[:,2] # slice out the names
    places = array[:,1] #slice out the places
    places = [list(set(places)).index(place) for place in places] #convert the places to ints
    pairs = zip(names,places) #combine the lists
    dict = {}
    for name in set(names): #step through each name
        dict[name] = [x[1] for x in pairs where x[0] == name]

不是最漂亮的代码,但它应该工作。你知道吗

相关问题 更多 >

    热门问题