check if value in tuple of dataframe

Viewed 2494

I have huge a dataframe (38 milj rows):

df = pd.DataFrame({'I':[1,2,3,4], 'C':[80,160,240,80],
                   'F':[(1,2,3,4),(5,7,2),(9,6,2,5,7),(4,0,8,3,2)]})

     C                F  I
0   80     (1, 2, 3, 4)  1
1  160        (5, 7, 2)  2
2  240  (9, 6, 2, 5, 7)  3
3   80  (4, 0, 8, 3, 2)  4

Now I would like to filter out the rows which contain the number 3 in 'F'

To give:

     C                F  I
0   80     (1, 2, 3, 4)  1
3   80  (4, 0, 8, 3, 2)  4

Is there a high performant, low memory usage way to do this?

I tried np.equal((3), df['F'].values).all() but this obviously does not work

4 Answers

Use in with list comprehension if performance is important:

df = df[[3 in x for x in df['F']]]

Or:

df = df[df['F'].apply(set) >= set([3])]

print (df)
   I   C                F
0  1  80     (1, 2, 3, 4)
3  4  80  (4, 0, 8, 3, 2)

Performance (depends of the number of matched values, and of the length of df, too):

#[40000 rows x 3 columns]
df = pd.concat([df] * 10000, ignore_index=True)


In [166]: %timeit df[[3 in x for x in df['F']]]
5.57 ms ± 132 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [167]: %timeit df[df['F'].apply(lambda x: 3 in x)]
12.2 ms ± 625 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [170]:  %timeit df[df['F'].apply(set) >= set([3])]
29 ms ± 396 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [171]:  %timeit df[pd.DataFrame(df['F'].values.tolist()).eq(3).any(1)]
37.4 ms ± 248 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

Better structure, like pointed @jpp is create:

from itertools import chain

lens = df['F'].str.len()
df = pd.DataFrame({
    'I' : df['I'].values.repeat(lens),
    'C' : df['C'].values.repeat(lens),
    'F' : list(chain.from_iterable(df['F'].tolist()))
})
print (df)
    I    C  F
0   1   80  1
1   1   80  2
2   1   80  3
3   1   80  4
4   2  160  5
5   2  160  7
6   2  160  2
7   3  240  9
8   3  240  6
9   3  240  2
10  3  240  5
11  3  240  7
12  4   80  4
13  4   80  0
14  4   80  8
15  4   80  3
16  4   80  2

You should use in operator in combination with apply method by passing a lambda expression.

df[df['F'].apply(lambda x: 3 in x)]

Output

   I   C                F
0  1  80     (1, 2, 3, 4)
3  4  80  (4, 0, 8, 3, 2)

Is there a high performant, low memory usage way to do this?

No, there isn't. A series of tuples is not vectorised. It consists of a double layer of pointers, which is not suited to Pandas / NumPy. You can use hacks such as the str accessor or a list comprehension. Or, even, attempt to expand into a dataframe:

mask = pd.DataFrame(df['F'].values.tolist()).eq(3).any(1)

print(mask)

0     True
1    False
2    False
3     True
dtype: bool

But all of these are expensive. To improve performance, you should look to improve how data is structured before the series is constructed.

A simple apply inside a loc will do the trick

df.loc[df.F.apply(lambda t : 3 in t)]


    I   C   F
0   1   80  (1, 2, 3, 4)
3   4   80  (4, 0, 8, 3, 2)
Related