Francisco Cervera
Francisco Cervera

Reputation: 69

Is there a more pythonic way to write this?

I'm looking to make this a little more pythonic.

user_df[-1:]['status_id'].values[0] in {3,5}

I ititially tried user_id.ix[-1:, 'status_id'].isin([3,5]), but didn't work.

Any suggestions? The top version works, but looks a little weird.

Upvotes: 1

Views: 79

Answers (2)

jezrael
jezrael

Reputation: 862921

You can try:

user_id['status_id'].iloc[-1:].isin([3,5])

Sample:

user_id = pd.DataFrame({'status_id':[1,2,3]})
print (user_id)
   status_id
0          1
1          2
2          3

#iloc without : [-1] return scalar
print (user_id['status_id'].iloc[-1] in set({3,5}))
True

#iloc with : [-1:] return vector - Series
print (user_id['status_id'].iloc[-1:].isin([3,5]))
2    True
Name: status_id, dtype: bool

Upvotes: 4

Joran Beasley
Joran Beasley

Reputation: 113998

isin might be marginally faster (the more values that you have to check the more speed up you would notice ... but even for large sets its not going to be a huge difference ...(I doubt its any faster in this example... its probably a little slower) ... but val in set() is pretty dang pythonic (in fact much more so than pd.isin)

you are testing a single value against a set ... by using pandas.isin or numpy.in1d you will incure significant time overhead to move into C and back to python vs just using in and a set wich is an O(1) look up ... (in either case the time slice is non-existent on a human time scale)

Upvotes: 2

Related Questions