首页 技术 正文
技术 2022年11月8日
0 收藏 451 点赞 1,545 浏览 1177 个字

怎样解决python dataframe loc,iloc循环处理速度很慢的问题

1.问题说明

最近用DataFrame做大数据 处理,发现处理速度特别慢,追究原因,发现是循环处理时,loc,iloc速度都特别慢,当数据量特别大得时候真的是超级慢。查很多资料,发现没有详细说明,以下为解决办法

2.问题解决

使用 Pandas.Series.apply 方法,可以对一列数据快速进行处理

Series.apply(*func*, *convert_dtype=True*, *args=()*, **\*kwds*)

函数说明:

To lunch typora from Terminal, you could add

func : function
convert_dtype : boolean, default True
Try to find better dtype for elementwise function results. If False, leave as dtype=object
args : tuple
Positional arguments to pass to function in addition to the value
Additional keyword arguments will be passed as keywords to the function

例子讲解

# 首先导入数据
>>> import pandas as pd
>>> import numpy as np
>>> series = pd.Series([20, 21, 12], index=['London','New York','Helsinki'])
>>> series
London 20
New York 21
Helsinki 12
dtype: int64# 应用1,把每个值都*2
>>> def square(x):
... return x**2
>>> series.apply(square)
London 400
New York 441
Helsinki 144
dtype: int64
>>> series.apply(lambda x: x**2)
London 400
New York 441
Helsinki 144
dtype: int64# 应用2,相减
>>> def subtract_custom_value(x, custom_value):
... return x-custom_value
>>> series.apply(subtract_custom_value, args=(5,))
London 15
New York 16
Helsinki 7
dtype: int64# 使用numpy library中得函数
>>> series.apply(np.log)
London 2.995732
New York 3.044522
Helsinki 2.484907
dtype: float64

3.总结

这样可以快速操作一列数据,不必循环操作每行每列数据,对于大数据处理是非常有用的

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,491
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,906
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,739
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,492
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,131
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,293