简体   繁体   中英

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.

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

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM