【问题标题】:From Pandas series, create dictionary with unique elements as keys, and their indices as values从 Pandas 系列中,创建以唯一元素为键、索引为值的字典
【发布时间】:2020-01-24 00:11:33
【问题描述】:

目标是从 pandas 列(系列)创建一个字典,其中键是列的唯一元素,值是元素出现的行索引。我目前有完成此操作的代码,但我想知道是否有更简单且不那么 hacky 的方法来做到这一点:

df = pd.DataFrame(np.random.randint(0,100,size=(1000, 4)), columns=list('ABCD'))
idx = df['A'].reset_index().groupby('A')['index'].apply(tuple).to_dict()

【问题讨论】:

  • 如果你问我,我认为这条线非常简洁。你不是在这里做类似的事情吗? stackoverflow.com/questions/49011261/…
  • 是的,从那以后我一直在使用这种方法,但我想知道是否还有更多的pythonic方法。
  • 如果@Jezrael 做不到,我就退出编码。
  • 我要测试,但我认为这是最好的方法
  • 你能用 Series 代替元组或列表吗?

标签: python pandas


【解决方案1】:

这是 GroupBy 对象的groups 属性。它返回一个具有唯一值的字典,作为原始数据帧的键和Index 对象。

df.groupby('A').groups

{0: Int64Index([61, 466, 505, 619, 697, 811, 872], dtype='int64'),
 1: Int64Index([125, 254, 278, 330, 390, 396, 670, 732, 748, 849, 871, 880, 882,
                908, 943], dtype='int64'),
 2: Int64Index([77, 283, 401, 543, 544, 693, 816], dtype='int64'),
 ...}

或者如果你真的需要元组:

{k: tuple(v) for k,v in df.groupby('A').groups.items()}

【讨论】:

    【解决方案2】:

    你可以的

    d = {x : y['index'].tolist() for x , y in df.reset_index().groupby(list(df))}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-05
      • 2018-08-25
      • 2013-05-12
      • 2017-02-28
      • 2017-04-25
      • 2022-01-17
      • 1970-01-01
      • 2020-09-12
      相关资源
      最近更新 更多