Pandas - 当字符串匹配时选择两个值之间的所有行

Tip*_*ena 2 python pandas

我有两个数据帧:

import pandas as pd
import numpy as np
d = {'fruit': ['apple', 'pear', 'peach'] * 5, 'values': np.random.randint(0,1000,15)}
df = pd.DataFrame(data=d)

d2 = {'fruit': ['apple', 'pear', 'peach'] * 2, 'min': [43, 196, 143, 174, 510, 450], 'max': [120, 310, 311, 563, 549, 582]}
df2 = pd.DataFrame(data=d2)
Run Code Online (Sandbox Code Playgroud)

我想选择所有的行df匹配fruitdf2 values之间minmax

我正在尝试类似的东西:

df.loc[df['fruit'].isin(df2['fruit'])].loc[df['values'].between(df2['min'], df2['max'])]
Run Code Online (Sandbox Code Playgroud)

但可以预见的是,这将返回一个 ValueError:只能比较标记相同的系列对象。

编辑:您会注意到fruitdf2. 这是故意的。我还在试图抓住之间的行minmax方法同上,只是我不只是要折叠的水果占据了绝对的行minmax

例如,在df1where fruit== 'apple' 中,我想要values43-120 和 174-563 之间的所有行。

Uts*_*Uts 5

df3 = df.merge(df2, on='fruit', how='inner') # Thanks for Henry Ecker for suggesting inner join
df3 = df3.loc[(df3['min'] < df3['values']) & (df3['max'] > df3['values'])]
df3
Run Code Online (Sandbox Code Playgroud)

输出

    fruit   values  min max
3   apple   883     467 947
6   apple   805     467 947
9   apple   932     467 947
11  peach   331     307 618
12  apple   665     467 947
Run Code Online (Sandbox Code Playgroud)

如果我们不想minmax输出山坳

df3 = df3.drop(columns=['min', 'max'])
df3
Run Code Online (Sandbox Code Playgroud)

输出

    fruit   values
3   apple   883
6   apple   805
9   apple   932
11  peach   331
12  apple   665
Run Code Online (Sandbox Code Playgroud)