Pandas.apply允许用户传递函数并将其应用于Pandas系列的每个单个值。这是对 Pandas 库的一项重大改进,因为此功能有助于根据所需条件将数据隔离,从而有效地将其用于数据科学和机器学习。
安装:
在终端上使用以下命令将Pandas模块导入python文件:
pip install pandas
要读取csv文件并将其压缩为pandas系列,请使用以下命令:
import pandas as pd
s = pd.read_csv("stock.csv", squeeze=True)
用法:
s.apply(func, convert_dtype=True, args=())
参数:
func:.apply接受一个函数并将其应用于pandas系列的所有值。
convert_dtype:根据函数的操作转换dtype。
args =():传递给函数而不是序列的其他参数。
返回类型:应用功能/操作后的 Pandas 系列。
对于数据集,请单击此处下载。
范例1:
以下示例传递一个函数,并依次检查每个元素的值,并相应地返回低,正常或高。
import pandas as pd
# reading csv
s = pd.read_csv("stock.csv", squeeze = True)
# defining function to check price
def fun(num):
if num<200:
return "Low"
elif num>= 200 and num<400:
return "Normal"
else:
return "High"
# passing function to apply and storing returned series in new
new = s.apply(fun)
# printing first 3 element
print(new.head(3))
# printing elements somewhere near the middle of series
print(new[1400], new[1500], new[1600])
# printing last 3 elements
print(new.tail(3))
输出:
范例2:
在以下示例中,使用lambda在.apply自身中制作了一个临时匿名函数。它将每个序列的值加5,然后返回一个新的序列。
import pandas as pd
s = pd.read_csv("stock.csv", squeeze = True)
# adding 5 to each value
new = s.apply(lambda num : num + 5)
# printing first 5 elements of old and new series
print(s.head(), '\n', new.head())
# printing last 5 elements of old and new series
print('\n\n', s.tail(), '\n', new.tail())
输出:
0 50.12
1 54.10
2 54.65
3 52.38
4 52.95
Name: Stock Price, dtype: float64
0 55.12
1 59.10
2 59.65
3 57.38
4 57.95
Name: Stock Price, dtype: float64
3007 772.88
3008 771.07
3009 773.18
3010 771.61
3011 782.22
Name: Stock Price, dtype: float64
3007 777.88
3008 776.07
3009 778.18
3010 776.61
3011 787.22
Name: Stock Price, dtype: float64
观察到,新值=旧值+ 5
本文介绍了Pandas库中的apply函数,该函数可以将自定义函数应用于Pandas Series的每一个值,实现数据的有效处理和转换。通过两个示例展示了如何使用apply函数进行条件判断和算术运算。
1009

被折叠的 条评论
为什么被折叠?



