如何优化Python代码

2024-05-06 19:39:33 发布

您现在位置:Python中文网/ 问答频道 /正文

全部

我将使用以下python代码计算一些特征值。但是,由于输入的大小太大,因此非常耗时。请帮我优化代码。你知道吗

  leaving_volume=len([x for x in pickup_ids if x not in dropoff_ids])
  arriving_volume=len([x for x in dropoff_ids if x not in pickup_ids])
  transition_volume=len([x for x in dropoff_ids if x in pickup_ids])

  union_ids=list(set(pickup_ids + dropoff_ids))
  busstop_ids=[x for x in union_ids if self.geoitems[x].fare>0]
  busstop_density=np.sum([Util.Geodist(self.geoitems[x].orilat, self.geoitems[x].orilng, self.geoitems[x].destlat, self.geoitems[x].destlng)/(1000*self.geoitems[x].fare) for x in busstop_ids])/len(busstop_ids) if len(busstop_ids) > 0 else 0
  busstop_ids=[x for x in union_ids if self.geoitems[x].balance>0]
  smartcard_balance=np.sum([self.geoitems[x].balance for x in busstop_ids])/len(busstop_ids) if len(busstop_ids) > 0 else 0

大家好

这是我的修订版。我在GPS跟踪数据上运行这个代码。速度更快。你知道吗

intersect_ids=set(pickup_ids).intersection( set(dropoff_ids) )
union_ids=list(set(pickup_ids + dropoff_ids))
leaving_ids=set(pickup_ids)-intersect_ids
leaving_volume=len(leaving_ids)
arriving_ids=set(dropoff_ids)-intersect_ids
arriving_volume=len(arriving_ids)
transition_volume=len(intersect_ids)

busstop_density=np.mean([Util.Geodist(self.geoitems[x].orilat, self.geoitems[x].orilng, self.geoitems[x].destlat, self.geoitems[x].destlng)/(1000*self.geoitems[x].fare) for x in union_ids if self.geoitems[x].fare>0])
if not busstop_density > 0:
    busstop_density = 0
smartcard_balance=np.mean([self.geoitems[x].balance for x in union_ids if self.geoitems[x].balance>0])
if not smartcard_balance > 0:
    smartcard_balance = 0

非常感谢你的帮助。你知道吗


Tags: inselfidsforlenifunionbalance
2条回答

我只能支持机器耶宁在这篇文章中所写的。如果您正在考虑切换到numpy,那么如果您的变量picku id和dropoff id是numpy数组(可能它们已经是了),那么您可以:

dropoff_ids = np.array( dropoff_ids, dtype='i' )
pickup_ids = np.array( pickup_ids, dtype='i' )

然后你就可以利用这些函数了np.IND公司()这将为您提供一个真/假数组,您只需对其求和即可得到真项目的总数。你知道吗

leaving_volume   = (-np.in1d( pickup_ids, dropoff_ids )).sum()
transition_volume= np.in1d( dropoff_ids, pickup_ids).sum()
arriving_volume  = (-np.in1d( dropoff_ids, pickup_ids)).sum()

不知何故,我有一种感觉,即过渡音量=len(皮卡id)-到达音量,但我现在不是100%确定。你知道吗

另一个对你有用的功能是np.唯一()如果您想消除重复的条目,这将使数组变成一个集合。你知道吗

我注意到了一些关于Python效率的琐事:

if x not in dropoff_ids

使用in运算符检查成员身份在set上比在list上更有效。但是用for遍历list可能比在set上更有效。因此,如果您希望前两行尽可能高效,您应该事先准备好这两种类型的数据结构。你知道吗

list(set(pickup_ids + dropoff_ids))

在合并数据之前创建集合比创建长的list并从中构造set更有效。幸运的是,您现在可能已经有了set版本(参见第一条注释)!你知道吗

首先,你需要问自己一个问题:

Is the time I save by constructing extra data structures worth the time it takes to construct them?

下一个:

np.sum([...])

我接受过Python的训练,可以考虑构造一个list,然后应用一个理论上只需要生成器作为code smell的函数。我不确定这是否适用于numpy,因为据我所知,从生成器中提取数据并将其放入numpy结构并不完全简单。你知道吗

看起来这只是代码的一小部分。如果您真的关心效率,我建议您使用numpy数组而不是列表,并尽可能地使用numpy的内置数据结构和函数。与内置的Python函数相比,它们可能更适合于C中的原始数据处理。你知道吗

如果你真的,真的关心效率,那么你应该直接用C语言进行数据分析。特别是如果你没有比你在这里介绍的更多的代码,那么翻译起来可能非常容易。你知道吗

相关问题 更多 >