我有两个数据帧:
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
匹配fruit
到df2
与 values
之间min
和max
。
我正在尝试类似的东西:
df.loc[df['fruit'].isin(df2['fruit'])].loc[df['values'].between(df2['min'], df2['max'])]
Run Code Online (Sandbox Code Playgroud)
但可以预见的是,这将返回一个 ValueError:只能比较标记相同的系列对象。
编辑:您会注意到fruit
在df2
. 这是故意的。我还在试图抓住之间的行min
和max
方法同上,只是我不只是要折叠的水果占据了绝对的行min
和max
。
例如,在df1
where fruit
== 'apple' 中,我想要values
43-120 和 174-563 之间的所有行。
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)
如果我们不想min
和max
输出山坳
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)
归档时间: |
|
查看次数: |
67 次 |
最近记录: |