wanderweeer
wanderweeer

Reputation: 459

operator module and pandas

I would like to allow the user to input an operator. Is it possible to use the operator module to select values in a pandas dataframe? I've tried the following:

import pandas as pd
import operator

In [7]: df=pd.DataFrame(ab,columns=['numbers','letters'])

In [8]: print(df)
   numbers letters
0       10       a
1        5       b
2        8       c
3       11       d
4       15       e

I've tried this to get all values <10:

df1=operator.lt(df[df['numbers'],10])

But I get the following error message:

TypeError: 'Series' objects are mutable, thus they cannot be hashed

I'm new to pandas and am wondering if I'm just missing something obvious.

Upvotes: 1

Views: 538

Answers (1)

MSeifert
MSeifert

Reputation: 152677

You need to make the DataFrame indexing after the operator call:

df1=df[operator.lt(df['numbers'],10)]

Because operator.lt returns a boolean Series, which can be used by df[...] as index. It's called boolean array indexing.

However, if you don't actually need the operator module you could just write:

df[df['numbers'] < 10]

Upvotes: 3

Related Questions