【问题标题】:Looping dictionary through column using Pandas使用 Pandas 在列中循环字典
【发布时间】:2018-12-30 13:08:00
【问题描述】:

我有一个数据框,其中有一列名为“输入”,由各种数字组成。

我创建了一个看起来像这样的字典

sampleDict = {
    "a" : ["123","456"],
    "b" : ["789","272"]
}

我正在尝试针对这本字典循环遍历“输入”列。如果找到字典中的任何值(123、789 等),我想在我的数据框中创建一个新列来表示它的找到位置。

例如,当在“输入”中找到 456 时,我想创建名为“found”的列,其中值为“a”。在输入中找到 789 时,该值为“b”。

我尝试了以下代码,但我的逻辑似乎不正确:

for key in sampleDict:
    for p_key in df['Input']:
           if code in p_key:
                if code in sampleDict[key]:
                    df = print(code)
print(df)

【问题讨论】:

    标签: python pandas loops for-loop


    【解决方案1】:

    使用列表推导创建掩码,然后将列表转换为数组并掩码搜索数组中的真实值

    sampleDict = {
        "a" : ["123","456"],
        "b" : ["789","272"]
    }
    
    search=['789','456','100']
    
    #https://www.techbeamers.com/program-python-list-contains-elements/
    #https://stackoverflow.com/questions/10274774/python-elegant-and-efficient-ways-to-mask-a-list
    
    for key,item in sampleDict.items():
       print(item)
       mask=[]
       [mask.append(x in search) for x in item]
       arr=np.array(item)
       print(arr[mask])
    

    【讨论】:

      【解决方案2】:

      您可以使用collections.defaultdict 构造列表值到键的映射。来自@jezrael 的数据。

      from collections import defaultdict
      
      d = defaultdict(list)
      
      for k, v in sampleDict.items():
          for w in v:
              d[w].append(k)
      
      print(d)
      
      defaultdict(list,
                  {'123': ['a'], '272': ['b'], '456': ['a'], '789': ['a', 'b']})
      

      然后使用pd.Series.map 将输入映射到新系列中的键:

      df = pd.DataFrame({'Input':['789','456','100']})
      df['found'] = df['Input'].map(d)
      
      print(df)
      
        Input   found
      0   789  [a, b]
      1   456     [a]
      2   100     NaN
      

      【讨论】:

        【解决方案3】:

        通过扁平列表将map 用于字典,只需要列表中的所有值都是唯一的:

        d = {k: oldk for oldk, oldv in sampleDict.items() for k in oldv}
        print (d)
        {'123': 'a', '456': 'a', '789': 'b', '272': 'b'}
        
        df = pd.DataFrame({'Input':['789','456','100']})
        df['found'] = df['Input'].map(d)
        print (df)
          Input found
        0   789     b
        1   456     a
        2   100   NaN
        

        如果lists 中的重复值可能使用聚合,例如join 第一步,map Series

        sampleDict = {
            "a" : ["123","456", "789"],
            "b" : ["789","272"]
        }
        
        
        df1 = pd.DataFrame([(k,  oldk) for oldk, oldv in sampleDict.items() for k in oldv], 
                            columns=['a','b'])
        s = df1.groupby('a')['b'].apply(', '.join)
        print (s)
        a
        123       a
        272       b
        456       a
        789    a, b
        Name: b, dtype: object
        
        df = pd.DataFrame({'Input':['789','456','100']})
        df['found'] = df['Input'].map(s)
        print (df)
          Input found
        0   789  a, b
        1   456     a
        2   100   NaN
        

        【讨论】:

          猜你喜欢
          • 2018-08-18
          • 2020-08-03
          • 2017-05-09
          • 2017-04-05
          • 1970-01-01
          • 1970-01-01
          • 2022-01-05
          • 2018-04-18
          • 2017-05-26
          相关资源
          最近更新 更多