在多个条件下过滤数据帧

Nig*_*ker 5 python dataframe pandas

data = {'year': ['11:23:19', '11:23:19', '11:24:19', '11:25:19', '11:25:19', '11:23:19', '11:23:19', '11:23:19', '11:23:19', '11:23:19'],
                'store_number': ['1944', '1945', '1946', '1948', '1948', '1949', '1947', '1948', '1949', '1947'],
                'retailer_name': ['Walmart', 'Walmart', 'CRV', 'CRV', 'CRV', 'Walmart', 'Walmart', 'CRV', 'CRV', 'CRV'],
                'amount': [5, 5, 8, 6, 1, 5, 10, 6, 12, 11],
                'id': [10, 10, 11, 11, 11, 10, 10, 11, 11, 10]}

        stores = pd.DataFrame(data, columns=['retailer_name', 'store_number', 'year', 'amount', 'id'])
        stores.set_index(['retailer_name', 'store_number', 'year'], inplace=True)
        stores_grouped = stores.groupby(level=[0, 1, 2])
Run Code Online (Sandbox Code Playgroud)

看起来像:

                                     amount  id
retailer_name store_number year                
Walmart       1944         11:23:19       5  10
              1945         11:23:19       5  10
CRV           1946         11:24:19       8  11
              1948         11:25:19       6  11
                           11:25:19       1  11
Walmart       1949         11:23:19       5  10
              1947         11:23:19      10  10
CRV           1948         11:23:19       6  11
              1949         11:23:19      12  11
              1947         11:23:19      11  10
Run Code Online (Sandbox Code Playgroud)

我设法过滤: stores_grouped.filter(lambda x: (len(x) == 1))

但是当我想要在两个条件下过滤时:

我的组长度为1,id列等于10.任何想法都这样做吗?

EdC*_*ica 3

实际上,正如filter预期的标量一样,您可以像普通样式语句bool一样添加条件:lambdaif

\n\n
In [180]:\nstores_grouped.filter(lambda x: (len(x) == 1 and x['id'] == 10))\n\xe2\x80\x8b\nOut[180]:\n                                     amount  id\nretailer_name store_number year                \nWalmart       1944         11:23:19       5  10\n              1945         11:23:19       5  10\n              1949         11:23:19       5  10\n              1947         11:23:19      10  10\nCRV           1947         11:23:19      11  10\n
Run Code Online (Sandbox Code Playgroud)\n