循环遍历列的有效方法

2024-10-01 19:27:04 发布

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

我的数据集如下所示:

import pandas as pd
data = {'stringID':['AB CD Efdadasfd','RFDS EDSfdsadf dsa','FDSADFDSADFFDSA']}
data = pd.DataFrame(data)
data['Index1'] = [[3,6],[7,9],[5,6]]
data['Index2'] = [[4,8],[10,13],[8,9]]

enter image description here

我根据Index1和Index2(都是列表)中的值计算了一个体积,我使用索引从stringID列中切片子字符串。下面是我的计算结果:

data['Value1'] = [data['stringID'][i][data['Index1'][i][0]:data['Index2'][i][0]] for i in range(0,len(data['stringID']))]

enter image description here

它可以工作,但是如果我在一个大数据集中循环它,速度会非常慢。有什么更好的方法?谢谢


Tags: 数据importpandasdataabascdpd
2条回答

编辑

正如您所说,您的真实数据集有3个以上的列,您只需在获取numpy nd array之前对3个列进行切片,如下所示:

data['Value1'] = [x[y[0]:z[0]] for x, y, z 
                           in  data[['stringID','Index1','Index2']].to_numpy()]

你无法避免循环。但是,您可以使用numpy nd array作为源来简化列表理解,以加快它的速度,例如

data['Value1'] = [x[y[0]:z[0]] for x,y,z in data.to_numpy()]

在300K行上计时

data = pd.concat([data]*100000, ignore_index=True)

In [1380]: %timeit [x[y[0]:z[0]] for x,y,z in data.to_numpy()]
617 ms ± 24.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [1382]: %timeit  [data['stringID'][i][data['Index1'][i][0]:data['Index2'][i][0]] for i in range(0,len(data['stringID']))]
11.3 s ± 320 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

因此,它比您的解决方案快大约18倍

您可以使用DataFrame.apply

data['Value1'] = data.apply(lambda d: d['stringID'][d['Index1'][0]:d['Index2'][0]], axis=1)

您可以预处理索引以用于在另一列中进行切片

from operator import itemgetter

data['slice'] = list(zip(data['Index1'].apply(itemgetter(0)), data['Index2'].apply(itemgetter(0))))
data['Value1'] = data.apply(lambda d: d['stringID'][slice(*d['slice'])], axis=1)

或者将切片对象直接存储在另一列中

data['slice'] = list(map(lambda x: slice(*x), zip(data['Index1'].apply(itemgetter(0)), 
                                                  data['Index2'].apply(itemgetter(0)))))


data['Value1'] = data.apply(lambda d: d['stringID'][d['slice']], axis=1)

相关问题 更多 >

    热门问题