[英]Is there a more pythonic way to write this?
I'm looking to make this a little more pythonic. 我正在寻找使它更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. 我最初尝试了
user_id.ix[-1:, 'status_id'].isin([3,5])
,但是没有用。
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
) isin
可能略快(您必须检查的值越多,您会注意到的越快...但是即使对于大型集合,它也不会有很大的不同...(我怀疑在此示例中它的速度是否更快)。 ..它可能会慢一些)...但是val in set()
非常 pd.isin
(实际上比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 ) 您正在针对一个
set
测试单个值 ...通过使用pandas.isin
或numpy.in1d
您将确保大量时间开销转移到C并返回到python in
而不是仅使用in
并且集合是O(1)
外观向上...( 无论哪种情况,在人类时间尺度上都不存在时间片 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.