Pandas列高效处理方法:字符串浮点列表取首尾值求和优化
Pandas字符串浮点列表列的最值对数和高效计算方案
问题背景
现有Pandas的某一列,每个元素都是空格分隔的浮点值字符串,需要对每个字符串对应的数值列表,分别筛选最大3个值、最小3个值计算对数求和。
最初实现方案效率极低,处理100万行数据耗时极长,代码如下:
import math from tqdm import tqdm for index,rows in tqdm(data.iterrows()): s=rows['prob_tokens'].split(' ') x=[float(elem) for elem in s] x.sort() high_sum=0 low_sum=0 try: low_sum = math.log(x[0])+math.log(x[1])+math.log(x[2]) except: low_sum=-10000000 try: high_sum= math.log(x[-3])+math.log(x[-1])+math.log(x[-2]) except: high_sum=-10000000 data.loc[index,'high_sum']=high_sum data.loc[index,'low_sum']=low_sum
示例数据
| prob_tokens | high_sum | low_sum |
|---|---|---|
| 0.028424 0.000922 0.037654 0.563366 0.99988 0.916362 0.356194 | -0.29 | -5.037 |
优化方案
df.apply()无法利用向量化特性,因此改用遍历DataFrame索引的方式处理,支持行并行处理,和普通的行遍历有本质区别。通过timeit在10万行Pandas数据集上测试性能:df.apply耗时103.8秒,索引遍历方式仅耗时12.2秒。
优化后代码如下:
import math def ffrow(data): s=data.split(" ") x = [float(elem) for elem in s] x.sort() high_sum = 0 low_sum = 0 try: low_sum = math.log(x[0])+math.log(x[1])+math.log(x[2]) except: low_sum = -10000000 try: high_sum = math.log(x[-3])+math.log(x[-1])+math.log(x[-2]) except: high_sum = -10000000 return high_sum,low_sum def fastapply(df): hs=[] ls=[] for i in range(0,len(df)): h,l=ffrow(df.iloc[i]['prob_tokens']) hs.append(h) ls.append(l) return hs,ls hs=fastapply(dataxx) dataxx['high_sum']=hs[0] dataxx['low_sum']=hs[1]
内容的提问来源于stack exchange,提问作者shubh gupta
相关产品推荐
相关产品推荐

