22、apply自定義函數(shù)

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.])
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容