Python?pandas中apply函數(shù)簡(jiǎn)介以及用法詳解
1.基本信息
? Pandas 的 apply()
方法是用來(lái)調(diào)用一個(gè)函數(shù)(Python method),讓此函數(shù)對(duì)數(shù)據(jù)對(duì)象進(jìn)行批量處理。Pandas 的很多對(duì)象都可以使用 apply()
來(lái)調(diào)用函數(shù),如 Dataframe、Series、分組對(duì)象、各種時(shí)間序列等。
2.語(yǔ)法結(jié)構(gòu)
? apply()
使用時(shí),通常放入一個(gè) lambda
函數(shù)表達(dá)式、或一個(gè)函數(shù)作為操作運(yùn)算,官方上給出DataFrame的 apply()
用法:
DataFrame.apply(self, func, axis=0, raw=False, result_type=None, args=(), **kwargs)
參數(shù):
- func:函數(shù)或 lambda 表達(dá)式,應(yīng)用于每行或者每列
- axis:{0 or ‘index’, 1 or ‘columns’}, 默認(rèn)為0
- 0 or ‘index’: 表示函數(shù)處理的是每一列
- 1 or ‘columns’: 表示函數(shù)處理的是每一行
- raw:bool 類(lèi)型,默認(rèn)為 False;
- False ,表示把每一行或列作為 Series 傳入函數(shù)中;
- True,表示接受的是 ndarray 數(shù)據(jù)類(lèi)型;
- result_type:{‘expand’, ‘reduce’, ‘broadcast’, None}, default None
These only act when axis=1 (columns):
- ‘expand’ : 列表式的結(jié)果將被轉(zhuǎn)化為列。
- ‘reduce’ : 如果可能的話(huà),返回一個(gè) Series,而不是展開(kāi)類(lèi)似列表的結(jié)果。這與 expand 相反。
- ‘broadcast’ : 結(jié)果將被廣播到 DataFrame 的原始形狀,原始索引和列將被保留。
- args: func 的位置參數(shù)
- **kwargs:要作為關(guān)鍵字參數(shù)傳遞給 func 的其他關(guān)鍵字參數(shù),1.3.0 開(kāi)始支持
返回值:
- Series 或者 DataFrame:沿?cái)?shù)據(jù)的給定軸應(yīng)用 func 的結(jié)果
Objects passed to the function are Series objects whose index is either the DataFrame's index (``axis=0``) or the DataFrame's columns(``axis=1``). 傳遞給函數(shù)的對(duì)象是Series對(duì)象,其索引是DataFrame的索引(axis=0)或DataFrame的列(axis=1)。 By default (``result_type=None``), the final return type is inferred from the return type of the applied function. Otherwise,it depends on the `result_type` argument. 默認(rèn)情況下( result_type=None),最終的返回類(lèi)型是從應(yīng)用函數(shù)的返回類(lèi)型推斷出來(lái)的。否則,它取決于' result_type '參數(shù)。
注:DataFrame與Series的區(qū)別與聯(lián)系:
區(qū)別:
- series,只是一個(gè)一維結(jié)構(gòu),它由index和value組成。
- dataframe,是一個(gè)二維結(jié)構(gòu),除了擁有index和value之外,還擁有column。
聯(lián)系:
- dataframe由多個(gè)series組成,無(wú)論是行還是列,單獨(dú)拆分出來(lái)都是一個(gè)series。
3.使用案例
3.1 DataFrame使用apply
官方使用案例
import pandas as pd import numpy as np df = pd.DataFrame([[4, 9]] * 3, columns=['A', 'B']) df A B 0 4 9 1 4 9 2 4 9 # 使用numpy通用函數(shù) (如 np.sqrt(df)), df.apply(np.sqrt) ''' A B 0 2.0 3.0 1 2.0 3.0 2 2.0 3.0 ''' # 使用聚合功能 df.apply(np.sum, axis=0) ''' A 12 B 27 dtype: int64 ''' df.apply(np.sum, axis=1) ''' 0 13 1 13 2 13 dtype: int64 ''' # 在每行上返回類(lèi)似列表的內(nèi)容 df.apply(lambda x: [1, 2], axis=1) ''' 0 [1, 2] 1 [1, 2] 2 [1, 2] dtype: object ''' # result_type='expand' 將類(lèi)似列表的結(jié)果擴(kuò)展到數(shù)據(jù)的列 df.apply(lambda x: [1, 2], axis=1, result_type='expand') ''' 0 1 0 1 2 1 1 2 2 1 2 ''' # 在函數(shù)中返回一個(gè)序列,生成的列名將是序列索引。 df.apply(lambda x: pd.Series([1, 2], index=['foo', 'bar']), axis=1) ''' foo bar 0 1 2 1 1 2 2 1 2 ''' # result_type='broadcast' 將確保函數(shù)返回相同的形狀結(jié)果 # 無(wú)論是 list-like 還是 scalar,并沿軸進(jìn)行廣播 # 生成的列名將是原始列名。 df.apply(lambda x: [1, 2], axis=1, result_type='broadcast') ''' A B 0 1 2 1 1 2 2 1 2 '''
其他案例:
import numpy as np import pandas as pd df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}, index=['a', 'b', 'c']) df A B C a 1 4 7 b 2 5 8 c 3 6 9 # 對(duì)各列應(yīng)用函數(shù) axis=0 df.apply(lambda x: np.sum(x)) A 6 B 15 C 24 dtype: int64 # 對(duì)各行應(yīng)用函數(shù) df.apply(lambda x: np.sum(x), axis=1) a 12 b 15 c 18 dtype: int64
3.2 Series使用apply
官網(wǎng)案例
s = pd.Series([20, 21, 12],index=['London', 'New York', 'Helsinki']) s ''' London 20 New York 21 Helsinki 12 dtype: int64 ''' # 定義函數(shù)并將其作為參數(shù)傳遞給 apply,求值平方化。 def square(x): return x ** 2 s.apply(square) ''' London 400 New York 441 Helsinki 144 dtype: int64 ''' # 通過(guò)將匿名函數(shù)作為參數(shù)傳遞給 apply s.apply(lambda x: x ** 2) ''' London 400 New York 441 Helsinki 144 dtype: int64 ''' # 定義一個(gè)需要附加位置參數(shù)的自定義函數(shù) # 并使用args關(guān)鍵字傳遞這些附加參數(shù)。 def subtract_custom_value(x, custom_value): return x - custom_value s.apply(subtract_custom_value, args=(5,)) ''' London 15 New York 16 Helsinki 7 dtype: int64 ''' # 定義一個(gè)接受關(guān)鍵字參數(shù)并將這些參數(shù)傳遞 # 給 apply 的自定義函數(shù)。 def add_custom_values(x, **kwargs): for month in kwargs: x += kwargs[month] return x s.apply(add_custom_values, june=30, july=20, august=25) ''' London 95 New York 96 Helsinki 87 dtype: int64 ''' # 使用Numpy庫(kù)中的函數(shù) s.apply(np.log) ''' London 2.995732 New York 3.044522 Helsinki 2.484907 dtype: float64 '''
3.3 其他案例
import pandas as pd # 顯示所有列 pd.set_option('display.max_columns', None) # 顯示所有行 pd.set_option('display.max_rows', None) # 設(shè)置value的顯示長(zhǎng)度為100,默認(rèn)為50 pd.set_option('max_colwidth', 100) # 用來(lái)計(jì)算日期差的包 import datetime def dataInterval(data1, data2): """ Args: :param data1: datetime :param data2: datetime :return: delta days """ d1 = datetime.datetime.strptime(data1, '%Y-%m-%d') d2 = datetime.datetime.strptime(data2, '%Y-%m-%d') delta = d1 - d2 return delta.days def getInterval(arrLike): """ Args: :param arrLike: DataFrame :return: delta days """ PublishedTime = arrLike['PublishedTime'] ReceivedTime = arrLike['ReceivedTime'] days = dataInterval(PublishedTime.strip(), ReceivedTime.strip()) return days def getInterval_new(arrLike, before, after): """ Args: :param arrLike: DataFrame :param before: forward time :param after: backwar time :return: delta days """ before = arrLike[before] after = arrLike[after] days = dataInterval(after.strip(), before.strip()) return days
if __name__ == '__main__': df = pd.read_excel('./data/NS_info.xls') print(df.head()) # method 1 df['TimeInterval'] = df.apply(getInterval, axis=1) print(df.head()) # method 2 df['TimeInterval'] = df.apply(getInterval_new,axis=1, args=('ReceivedTime', 'PublishedTime')) # method 3 df['TimeInterval'] = df.apply(getInterval_new,axis=1, **{'before': 'ReceivedTime', 'after': 'PublishedTime'}) # method 4 df['TimeInterval'] = df.apply(getInterval_new,axis=1, before='ReceivedTime', after='PublishedTime')
4.總結(jié)
1.apply方法都是通過(guò)傳入一個(gè)函數(shù)或者lambda表達(dá)式對(duì)數(shù)據(jù)進(jìn)行批量處理
2.apply方法處理的都是一個(gè)Series對(duì)象
參考鏈接:
1.https://blog.csdn.net/missyougoon/article/details/83301712
2.https://blog.csdn.net/qq_19528953/article/details/79348929
到此這篇關(guān)于Python pandas中apply函數(shù)簡(jiǎn)介以及用法詳解的文章就介紹到這了,更多相關(guān)pandas apply函數(shù)用法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 對(duì)pandas中apply函數(shù)的用法詳解
- pandas apply 函數(shù) 實(shí)現(xiàn)多進(jìn)程的示例講解
- 詳談pandas中agg函數(shù)和apply函數(shù)的區(qū)別
- 解析pandas apply() 函數(shù)用法(推薦)
- Pandas groupby apply agg 的區(qū)別 運(yùn)行自定義函數(shù)說(shuō)明
- pandas使用函數(shù)批量處理數(shù)據(jù)(map、apply、applymap)
- Pandas的Apply函數(shù)具體使用
- Pandas對(duì)每個(gè)分組應(yīng)用apply函數(shù)的實(shí)現(xiàn)
- Pandas中Apply函數(shù)加速百倍的技巧分享
相關(guān)文章
python爬取網(wǎng)易云音樂(lè)評(píng)論
這篇文章主要為大家詳細(xì)介紹了python爬取網(wǎng)易云音樂(lè)評(píng)論,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-11-11python實(shí)現(xiàn)的讀取網(wǎng)頁(yè)并分詞功能示例
這篇文章主要介紹了python實(shí)現(xiàn)的讀取網(wǎng)頁(yè)并分詞功能,結(jié)合實(shí)例形式分析了Python使用requests模塊讀取網(wǎng)頁(yè),以及jieba庫(kù)分詞的相關(guān)操作技巧,需要的朋友可以參考下2019-10-10利用Python自制網(wǎng)頁(yè)并實(shí)現(xiàn)一鍵自動(dòng)生成探索性數(shù)據(jù)分析報(bào)告
這篇文章主要介紹了利用Python自制了網(wǎng)頁(yè)并實(shí)現(xiàn)一鍵自動(dòng)生成探索性數(shù)據(jù)分析報(bào)告,文章內(nèi)容具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-05-05Python利用代理ip實(shí)現(xiàn)自動(dòng)化爬蟲(chóng)任務(wù)管理
本文主要介紹了Python利用代理ip實(shí)現(xiàn)自動(dòng)化爬蟲(chóng)任務(wù)管理,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06Python?matplotlib實(shí)戰(zhàn)之雷達(dá)圖繪制
雷達(dá)圖(Radar?Chart),也被稱(chēng)為蛛網(wǎng)圖或星型圖,是一種用于可視化多個(gè)變量之間關(guān)系的圖表形式,本文主要為大家介紹了如何使用Matplotlib繪制雷達(dá)圖,需要的小伙伴可以參考下2023-08-08Django啟動(dòng)時(shí)找不到mysqlclient問(wèn)題解決方案
這篇文章主要介紹了Django啟動(dòng)時(shí)找不到mysqlclient問(wèn)題解決方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11scrapy 遠(yuǎn)程登錄控制臺(tái)的實(shí)現(xiàn)
本文主要介紹了scrapy 遠(yuǎn)程登錄控制臺(tái)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02python安裝dlib庫(kù)報(bào)錯(cuò)問(wèn)題及解決方法
這篇文章主要介紹了python安裝dlib庫(kù)報(bào)錯(cuò)問(wèn)題及解決方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-03-03