【问题标题】:How to get a dictionary with keys equal to group members in dataframe and the values to the group ids?如何获取一个字典,其键等于数据框中的组成员和组 ID 的值?
【发布时间】:2016-10-27 13:27:33
【问题描述】:

我有一个如下的数据框:

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

我使用了 df.groupby('City'),对于上面的示例,我们将有 2 个组,即 1)Seattle 2)Portland。现在我想得到一个字典,其中键是名称,值是组 ID,即:

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

什么是有效的方法?

【问题讨论】:

  • 请发布您到目前为止所尝试的内容
  • 我不明白你的字典中的值是从哪里来的,你能解释一下你的逻辑吗?
  • 你在城市里groupby 真奇怪,当你真的想把名字作为组标题时。看看Pandas.DataFrame.to_dict()这个。

标签: python pandas


【解决方案1】:

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

    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]

不是最漂亮的代码,但它应该可以工作。

【讨论】:

    猜你喜欢
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多