python - 在多个条件下过滤数据框

标签 python pandas dataframe

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])

看起来像:

                                     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

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

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

我的组长度为 1,id 列等于 10。 知道怎么做吗?

最佳答案

实际上,filter 需要一个标量 bool,您可以像普通的 if 一样在 lambda 中添加条件> 风格声明:

In [180]:
stores_grouped.filter(lambda x: (len(x) == 1 and x['id'] == 10))
​
Out[180]:
                                     amount  id
retailer_name store_number year                
Walmart       1944         11:23:19       5  10
              1945         11:23:19       5  10
              1949         11:23:19       5  10
              1947         11:23:19      10  10
CRV           1947         11:23:19      11  10

关于python - 在多个条件下过滤数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38638565/

相关文章:

python - 计算引用具有 "nan"值的变量的 SymPy 表达式

Python aiohttp 请求停止但没有引发异常

Python O365 发送邮件

python - 对于两个 DataFrame 中的多列的自定义条件,比嵌套 for 循环更快的方法

python - 在多个时间范围内聚合/重采样 pandas 多索引数据帧并预测 ARIMA

python - 如何修复 : the python code doesn't work through DAG airflow: pandas. read_csv ('gs://x/y.csv' ) 文件不存在

python - 在 python 中从 VTK 文件中检索面和点

python dataframe根据其他列的条件替换列中的部分字符串

python - Pandas :如何获得每一行的百分比

python - 按多列分组的值的线图