Oeyvind
Oeyvind

Reputation: 357

Python Pandas filtering; TypeError: cannot convert the series to <class 'int'>

I have a DataFrame looking like this:

ID  Instrument  Units   Price   Status
165  WTICO_USD     -1   60.264  OPEN
169  WTICO_USD     -1   60.274  OPEN
173  WTICO_USD      1   54.284  OPEN
185  BCO_USD        1   60.124  OPEN

If I write the following, I get what I expect:

DF[(DF.Instrument=='WTICO_USD')]

And same with this:

DF[(DF.Instrument=='WTICO_USD')&(DF.ID==165)]

However, if I try to filter further, as in this, I get no rows:

DF[(DF.Instrument=='WTICO_USD')&(DF['Units']==-1)]

Same with

DF[(DF.Instrument=='WTICO_USD')&(DF.Units=='-1')]

However, this gives an error:

DF[(DF.Instrument=='WTICO_USD')&(DF['Units']>-1)]

TypeError: cannot convert the series to class 'int'

So, I try this and get another error:

DF.Units.applymap(int)

'Series' object has no attribute 'applymap'

So, since I select all values in the unit column, I get a series that I cannot convert. But why do I also get so when I try this?

DF[(DF.Instrument=='WTICO_USD')&(int(DF['Units'])>-1)]

cannot convert the series to class 'int'

How can I filter on all rows that are Instrument == WTICO_USD and have a Units < 0 ?

Upvotes: 1

Views: 8189

Answers (1)

Grr
Grr

Reputation: 16079

You could use DF.Units = DF.Units.map(int) or DF.Units = DF.Units.astype(int). From there your filters should work.

Just for reference Difference between map, applymap and apply methods in Pandas , gives a great explanation of the differences between apply, applymap, and map. You may notice that under the definitions of the methods applymap would be nonsensical on a series.

Upvotes: 3

Related Questions