我的数据集如下所示:
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]]
我根据Index1和Index2(都是列表)中的值计算了一个体积,我使用索引从stringID列中切片子字符串。下面是我的计算结果:
data['Value1'] = [data['stringID'][i][data['Index1'][i][0]:data['Index2'][i][0]] for i in range(0,len(data['stringID']))]
它可以工作,但是如果我在一个大数据集中循环它,速度会非常慢。有什么更好的方法?谢谢
编辑:
正如您所说,您的真实数据集有3个以上的列,您只需在获取numpy nd array之前对3个列进行切片,如下所示:
你无法避免循环。但是,您可以使用numpy nd array作为源来简化列表理解,以加快它的速度,例如
在300K行上计时:
因此,它比您的解决方案快大约18倍
您可以使用
DataFrame.apply
您可以预处理索引以用于在另一列中进行切片
或者将切片对象直接存储在另一列中
相关问题 更多 >
编程相关推荐