Francisco Cervera Francisco Cervera - 2 months ago 7
Python Question

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.

Answer

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
Comments