1、apply方法
apply函數(shù)可以接收一個自定義函數(shù), 可以將DataFrame的行/列數(shù)據(jù)傳遞給自定義函數(shù)處理
1.1、Series的apply方法
1、apply方法有一個func參數(shù), 把傳入的函數(shù)應(yīng)用于Series的每個元素
import pandas as pd
df = pd.DataFrame({'a': [10,20,30], 'b': [20,30,40]})
def my_sql(x):
return x**2
sq = df['a'].apply(my_sql)
print(sq)
#0 100
#1 400
#2 900
#Name: a, dtype: int64
2、apply 傳入 需要多個參數(shù)的函數(shù)
# 參數(shù) x, e
def my_exp(x, e):
return x**e
ex = df['a'].apply(my_exp, e=2)
print(ex)
1.2、DataFrame的apply方法
1、使用方法
axis 0(默認)按列處理,1按行處理
# DataFrame的整體數(shù)據(jù),my_sql為前面的函數(shù)
df.apply(my_sql, axis=0)
# a b
#0 100 400
#1 400 900
#2 900 1600
def avg_3_appy(col):
x = col[0]
y = col[1]
z = col[2]
return (x + y + z)/3
df.apply(avg_3_appy)
#a 20.0
#b 30.0
#dtype: float64
2、向量化函數(shù)
1、使用np.vectorize將函數(shù)向量化
def avg_2_mod(x, y):
if(x == 20):
return (np.NaN)
else:
return (x + y) / 2
import numpy as np
avg_2_mod_vec = np.vectorize(avg_2_mod)
avg_2_mod_vec(df['a'], df['b'])
# array([15., nan, 35.])
2、裝飾器使用
@np.vectorize
def avg_2_mod2(x, y):
if(x == 20):
return (np.NaN)
else:
return (x + y) / 2
avg_2_mod2(df['a'], df['b'])
# array([15., nan, 35.])