Pandas知識點(diǎn)-詳解表級操作管道函數(shù)pipe
pipe()參數(shù)和用法介紹
pipe(func, *args, **kwargs):
func: 用于對數(shù)據(jù)進(jìn)行表級處理的函數(shù),函數(shù)可以是內(nèi)置函數(shù)、庫函數(shù)、自定義函數(shù)或匿名函數(shù)。 *args: 傳遞給函數(shù)func的位置參數(shù)。 **kwargs: 傳遞給函數(shù)func的關(guān)鍵字參數(shù)。
返回?cái)?shù)據(jù):
返回一個(gè)新的DataFrame。
pipe()函數(shù)基本使用
# coding=utf-8
import pandas as pd
import numpy as np
df = pd.DataFrame({'Col-1': [1, 3, 5], 'Col-2': [5, 7, 9]})
print(df)
res = df.pipe(np.square)
print('-'*30, '\n', res, sep='')
Col-1 Col-2
0 1 5
1 3 7
2 5 9
------------------------------
Col-1 Col-2
0 1 25
1 9 49
2 25 81
如果只對DataFrame做一次處理,建議使用apply(),pipe()函數(shù)的精髓在于對DataFrame做多次處理時(shí),使用鏈?zhǔn)秸{(diào)用。
pipe()函數(shù)鏈?zhǔn)秸{(diào)用
df_one = np.square(df)
print('-'*30, '\n', df_one, sep='')
df_two = np.multiply(df_one, 2)
print('-'*30, '\n', df_two, sep='')
df_three = np.add(df_two, 10)
print('-'*30, '\n', df_three, sep='')
------------------------------
Col-1 Col-2
0 1 25
1 9 49
2 25 81
------------------------------
Col-1 Col-2
0 2 50
1 18 98
2 50 162
------------------------------
Col-1 Col-2
0 12 60
1 28 108
2 60 172
這三個(gè)函數(shù)也可以嵌套在一起,寫到一行代碼中。
result = np.add(np.multiply(np.square(df), 2), 10)
print('-'*30, '\n', result, sep='')
------------------------------
Col-1 Col-2
0 12 60
1 28 108
2 60 172
遇到類似的情況,非常適合使用pipe()來鏈?zhǔn)秸{(diào)用,提高可讀性。
pipe_result = df.pipe(np.square).pipe(np.multiply, 2).pipe(np.add, 10)
print('-'*30, '\n', pipe_result, sep='')
------------------------------
Col-1 Col-2
0 12 60
1 28 108
2 60 172
pipe_result = (df.pipe(np.square)
.pipe(np.multiply, 2)
.pipe(np.add, 10))
print('-'*30, '\n', pipe_result, sep='')
------------------------------
Col-1 Col-2
0 12 60
1 28 108
2 60 172
pipe()中func的另一種傳參方式
def add_num(num, dfx):
df_new = dfx.add(num)
return df_new
res = df.pipe((add_num, 'dfx'), 10)
print('-'*30, '\n', res, sep='')
res = df.pipe((add_num, 'dfx'), num=100)
print('-'*30, '\n', res, sep='')
------------------------------
Col-1 Col-2
0 11 15
1 13 17
2 15 19
------------------------------
Col-1 Col-2
0 101 105
1 103 107
2 105 109
參考文檔:
[1] pandas中文網(wǎng):https://www.pypandas.cn/docs/
相關(guān)閱讀??
Pandas知識點(diǎn)-詳解轉(zhuǎn)換函數(shù)transform
評論
圖片
表情
