使用Python Pandas根据第二个df中定义的bin将数据绑定到一个df中

时间:2014-09-03 19:42:15

标签: python join pandas dataframe binning

我试图根据第二个数据帧中定义的bin在一个数据帧中存储数据。我在想pd.bin和pd.merge的某些组合可能会让我在那里吗?

这基本上是每个数据帧当前的形式:

df = pd.DataFrame({'id':['a', 'b', 'c', 'd','e'],
                   'bin':[1, 2, 3, 3, 2],
                   'perc':[0.1,0.9,0.3,0.7,0.5]})

df2 = pd.DataFrame({'bin':[1, 1, 1, 2, 2, 2, 3, 3, 3], 
                    'result':['low', 'medium','high','low', 'medium','high','low', 'medium','high'],
                    'cut_min':[0,0.2,0.6,0,0.3,0.7,0,0.4,0.8],
                    'cut_max':[0.2,0.6,1,0.3,0.7,1,0.4,0.8,1]})

DF:

bin id  perc
1   a   0.1
2   b   0.9
3   c   0.3
3   d   0.7
2   e   0.5

这是带有垃圾箱的表格,df2:

bin cut_max cut_min result
1   0.2     0.0     low
1   0.6     0.2     medium
1   1.0     0.6     high
2   0.3     0.0     low
2   0.7     0.3     medium
2   1.0     0.7     high
3   0.4     0.0     low
3   0.8     0.4     medium
3   1.0     0.8     high

我想匹配bin,并使用包含df中perc值的cut_min和cut_max在df2中找到合适的结果。所以,我希望结果表看起来像这样:

bin id  perc    result
1   a   0.1     low
2   b   0.9     high
3   c   0.3     low
3   d   0.7     medium
2   e   0.5     medium

我最初是在一个SQL查询中写的,它通过连接完成了任务:

select
  df.id
  , df.bin
  , df.perc
  , df2.result
from df
inner join df2
  on df.bin = df2.bin
  and df.perc >= df2.cut_min 
  and df.perc < df2.cut_max

如果有人知道使用Pandas做到这一点的好方法,我们将不胜感激! (这实际上是我第一次找到解决方案只能在stackoverflow上找到解决方案,所以如果上述任何一个解释得不够好,我很抱歉!)

2 个答案:

答案 0 :(得分:4)

bin列上的第一个merge df and df2,然后是select the rows cut_min <= perc < cut_max

In [95]: result = pd.merge(df, df2, on='bin').query('cut_min <= perc < cut_max'); result
Out[95]: 
    bin id  perc  cut_max  cut_min  result
0     1  a   0.1      0.2      0.0     low
5     2  b   0.9      1.0      0.7    high
7     2  e   0.5      0.7      0.3  medium
9     3  c   0.3      0.4      0.0     low
13    3  d   0.7      0.8      0.4  medium

In [97]: result = result[['bin', 'id', 'perc', 'result']]

In [98]: result.sort('id')
Out[98]: 
    bin id  perc  result
0     1  a   0.1     low
5     2  b   0.9    high
9     3  c   0.3     low
13    3  d   0.7  medium
7     2  e   0.5  medium

答案 1 :(得分:0)

module bitstring 有一个名为 BitArray 的类,您可以使用字节数组对其进行初始化:

(您需要pip install bitarray

from bitstring import BitArray


BitArray(bytes = <byte_array>)