首先,合并pivoted[lower_limit]
回temp
。因此,对于temp
中的每个price
还有一个lower_limit
值。
temp = pd.merge(temp, pivoted['lower_limit'].reset_index(), on=ABC)
然后就可以限制你注意那些行中temp
的量,price
是> = lower_limit
:
result = temp.loc[temp['price'] >= temp['lower_limit']].groupby(ABC)['price'].min()
:
temp.loc[temp['price'] >= temp['lower_limit']]
期望的结果可通过计算groupby/min
中找到
例如,
个
import numpy as np
import pandas as pd
np.random.seed(2017)
N = 1000
ABC = list('ABC')
temp = pd.DataFrame(np.random.randint(2, size=(N,3)), columns=ABC)
temp['price'] = np.random.random(N)
pivoted = pd.pivot_table(temp, index=['A','B','C'],values=['price'],
aggfunc=[np.mean,np.std],fill_value=0)
pivoted['lower_limit'] = pivoted['mean'] - 2 * pivoted['std']
pivoted['upper_limit'] = pivoted['mean'] + 2 * pivoted['std']
temp = pd.merge(temp, pivoted['lower_limit'].reset_index(), on=ABC)
result = temp.loc[temp['price'] >= temp['lower_limit']].groupby(ABC)['price'].min()
print(result)
产量
A B C
0 0 0 0.003628
1 0.000132
1 0 0.005833
1 0.000159
1 0 0 0.006203
1 0.000536
1 0 0.001745
1 0.025713
惊人!这似乎工作正是我想要为你的例子 - 不是为了我的。我得到以下错误:'*之后的类型对象参数必须是可迭代的,而不是itertools.imap'可能是因为A,B,C中的值是日期对象? – Lula
'A','B','C'中的日期对象不会导致这个问题,但是一些迭代可能会导致这个问题。 (请参阅https://stackoverflow.com/q/31166814/190597。)如果这与您的情况看起来并不相似,请发布'temp.head()。reset_index()。to_dict('list')'。这将向我们展示前几行'temp'的明确表示。如果我们很幸运,它会让我们重现你所看到的错误。 – unutbu
我错了 - 您发布的示例在'A','B'和'C'中重现了不可迭代的 值的错误。我在猜测发生错误是因为temp的'A'列的dtype是'datetime64 [ns,UTC]',而'pivoted'的'A'索引 等级是'DatetimeIndex'。无论如何,有一个简单的解决方法:使用 pivoted ['lower_limit']。reset_index()'而不是使用 'pivoted ['lower_limit']。to_frame()'。我编辑了上面的代码以显示我的意思。 'reset_index'会将'A','B','C'索引级别移回到列中。因此合并操作将在 相同的dtypes之间。 – unutbu