从数据帧字典中,如何基于最接近值的一列获取特定行

时间:2019-08-21 11:03:41

标签: python pandas

我有三个数据框字典。所有三个字典的键都相同,并且数据框的格式都相同。

示例:

Dictionary 1      Dictionary 2      Dictionary 3
key   value       key   value       key   value
2     df1         2     df1         2     df1
16    df2         16    df2         16    df2
19    df3         19    df3         19    df3
etc...


Dictionary 1, df1:  
Index        col 1      col 2      col 3
218793       654        87         45
218837       6812       65464      64
218885       6545       8787       72
etc...

Dictionary 2, df1:  
Index        col 1      col 2      col 3
173265       4589       824        15
173380       56756      8567       45
173502       216        64         63
173545       1478       8665       76
etc...

Dictionary 3, df1: 
Index        col 1      col 2      col 3
318793       1125       899        47
318799       6547       83         49
318824       6          1158       64
318863       9963       224        69
etc... 

对于字典1中每个数据帧中的每一行,我想将此行加上其他与第3列的值最接近的其他数据帧/字典中的每一行相加,形成一个新的数据帧。

我尝试使用argsort遍历第一个字典以找到最接近的值,但我不是专家,无法弄清楚。

这是我目前的尝试

def matches(dict1, dict2, dict3)
   ans = pd.DataFrame()
   for k, v in dict1.items():
      for i in range(v):
      value = dict1[k].iloc[i,3] #this should be the col3 value
      ans.append(v)  # this should be each row in each df in dict1
      ans.append(dict2[k].iloc[((dict2[k])['col3']-value.abs().argsort()[:1]])
      ans.append(dict3[k].iloc[((dict3[k])['col3']-value.abs().argsort()[:1]])
   return ans

我了解这有多少错误,但是我尝试了很多不同的方法,我正在抽秸秆!

我要输出以下内容:

index   col 1       col 2       col 3
1       654         87          45       (from dict1, df1, row 1)
2       56756       8567        45       (from dict2, df1, row 2)
3       1125        899         47       (from dict3, df1, row 1)
4       6812        65464       64       (from dict1, df1, row 2)
5       216         64          63       (from dict2, df1, row 3)
6       6           1158        64       (from dict3, df1, row 3)
...
9652    4546        45454       1564     (from dict1, df62, row 56)
9653    4225        65          1564     (from dict2, df62, row 61)
9654    3326        272         1570     (from dict3, df62, row 49)
etc...

我没有尽头的错误,将它们放在这里毫无意义。

1 个答案:

答案 0 :(得分:0)

知道了

ans = pd.Dataframe()

for k,v in dict1.items():
    for i in v.col3:
        dict1_temp = (dict1[k].iloc[(dict1[k]['col3']-i)).abs().argsort()[:1]])
        dict2_temp = (dict2[k].iloc[(dict2[k]['col3']-i)).abs().argsort()[:1]])
        dict3_temp = (dict3[k].iloc[(dict3[k]['col3']-i)).abs().argsort()[:1]])

        ans = ans.append(temp1)
        ans = ans.append(temp2)
        ans = ans.append(temp3)

    return ans

如果有人有更有效的方法,我将不胜感激。

相关问题