更新:
使用以下数据框:
df = pd.DataFrame({
'value' : [4,2,5,6,7,8,6,5,4,1,2,4],
'date': fread_year_month(dt.datetime(2015, 1, 1),dt.datetime(2015, 12, 1)),
'stock': ['amzn']*12
},columns=[
'value', 'date', 'stock'] )
df2 = pd.DataFrame({
'value' : [1]*11,
'date': fread_year_month(dt.datetime(2015, 1, 1),dt.datetime(2015, 11, 1)),
'stock': ['msft']*11
},columns=[
'value', 'date', 'stock'] )
df = df.append(df2)
df.set_index(['stock', 'date'], inplace=True)
我做了以下事情:
In [1]: idx = pd.IndexSlice
In [2]: criterion = df.loc[idx[:,'2015-10-01':'2015-12-01'],:].\
groupby(level=0).agg(['count']) > 2
In [3]: criterion = criterion['value']['count']
In [4]: df2 = df.loc[idx[:,'2015-10-01':'2015-12-01'],:].groupby(level=0).sum()
In [5]: df3 = pd.DataFrame(columns=['value'], index=criterion[criterion==False].index)
In [6]: df2[criterion].append(df3, ignore_index=False)
Out[6]:
value
stock
amzn 7
msft NaN
在此示例中,MSFT 没有 2015-12 年的数据(它只有 3 个月中的 2 个月),因此根据我的要求将其值设置为 NaN。