日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python中raw函数_Python apply函数

發布時間:2023/12/18 python 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python中raw函数_Python apply函数 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1、介紹

apply函數是

pandas里面所有函數中自由度最高的函數。該函數如下:

DataFrame.apply(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), **kwds)

該函數最有用的是第一個參數,這個參數是函數,相當于C/C++的函數指針。

這個函數需要自己實現,函數的傳入參數根據axis來定,比如axis = 1,就會把一行數據作為Series的數據 結構傳入給自己實現的函數中,我們在函數中實現對Series不同屬性之間的計算,返回一個結果,則apply函數 會自動遍歷每一行DataFrame的數據,最后將所有結果組合成一個Series數據結構并返回。

2、樣例

import numpy as npimport pandas as pd

f = lambda x: x.max()-x.min()

df = pd.DataFrame(np.random.randn(4,3),columns=list('bde'),index=['utah', 'ohio', 'texas', 'oregon'])print(df)

t1 = df.apply(f)print(t1)

t2 = df.apply(f, axis=1)print(t2)

輸出結果如下所示:

b d e

utah 1.106486 0.101113 -0.494279ohio 0.955676 -1.889499 0.522151texas 1.891144 -0.670588 0.106530oregon -0.062372 0.991231 0.294464b 1.953516d 2.880730e 1.016430dtype: float64

utah 1.600766ohio 2.845175texas 2.561732oregon 1.053603dtype: float64

3、性能比較

df = pd.DataFrame({'a': np.random.randn(6), 'b': ['foo', 'bar'] * 3, 'c': np.random.randn(6)})def my_test(a, b): return a + bprint(df)

df['Value'] = df.apply(lambda row: my_test(row['a'], row['c']), axis=1) # 方法1print(df)

df['Value2'] = df['a'] + df['c'] # 方法2print(df)

輸出結果如下:

a b c

0 -1.194841 foo 1.648214

1 -0.377554 bar 0.496678

2 1.524940 foo -1.245333

3 -0.248150 bar 1.526515

4 0.283395 foo 1.282233

5 0.117674 bar -0.094462

a b c Value

0 -1.194841 foo 1.648214 0.453374

1 -0.377554 bar 0.496678 0.119124

2 1.524940 foo -1.245333 0.279607

3 -0.248150 bar 1.526515 1.278365

4 0.283395 foo 1.282233 1.565628

5 0.117674 bar -0.094462 0.023212

a b c Value Value2

0 -1.194841 foo 1.648214 0.453374 0.453374

1 -0.377554 bar 0.496678 0.119124 0.119124

2 1.524940 foo -1.245333 0.279607 0.279607

3 -0.248150 bar 1.526515 1.278365 1.278365

4 0.283395 foo 1.282233 1.565628 1.565628

5 0.117674 bar -0.094462 0.023212 0.023212

注意:當數據量很大時,對于簡單的邏輯處理建議方法2(個人處理幾百M數據集時,方法1花時200s左右,方法2花時10s)!!!

http://shenzhen.offcn.com/

總結

以上是生活随笔為你收集整理的python中raw函数_Python apply函数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。