&安培;一起列出布尔数据框架

时间:2018-02-28 10:56:55

标签: python pandas

我有一个pandas DataFrame:

import pandas as pd
import numpy as np
from random import sample, randrange
from functools import reduce

N = 200
df = pd.DataFrame({'Rating':    np.random.choice(range(100), N),
                   'Treatment': np.random.choice(range(1, 10), N),
                   'Trial':     np.random.choice(range(1, 20), N),
                   'Name':      np.random.choice(list("ABCDEF"), N),
                   'Target':    np.random.choice(list("JKLMNOP"), N),
                   'Part':      np.random.choice(list("WXYZ"), N),
                   })

在我的应用程序中,用户可以进行选择,但是现在让我们选择一些随机值:

>>> categories = [sorted(df[column].unique()) for column in df.columns.values]
>>> print(categories)
[['A', 'B', 'C', 'D', 'E', 'F'], ['W', 'X', 'Y', 'Z'], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 22, 23, 24, 25, 26, 27, 28, 29, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 78, 79, 80, 82, 84, 85, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99], ['J', 'K', 'L', 'M', 'N', 'O', 'P'], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]]
>>> selected = [sample(category, k=3) for category in categories]
>>> print(selected)
[['F', 'D', 'C'], ['X', 'Z', 'W'], [36, 35, 16], ['O', 'N', 'P'], [8, 1, 9], [7, 11, 8]]

现在我想在我的DataFrame中选择行,其中,对于每列,单元格的值在选择中。我想出的是:

>>> df[reduce((lambda x, y: x & y), [df[column].isin(selection) for (column, selection) in zip(df.columns.values, selected)])]
    Name Part  Rating Target  Treatment  Trial
173    D    Z      35      O          9      7

这样可行,但它看起来并不像pythonic。有更好的方法吗?

2 个答案:

答案 0 :(得分:4)

对数据框使用xxxx.xx/admin/和dict

isin

答案 1 :(得分:3)

您可以使用numpy.logical_and.reduce

df[np.logical_and.reduce([df[i].isin(j) for i, j in zip(df.columns, selected)])]

这会将布尔数组列表缩减为单个布尔数组以进行索引。