panda中的apply()方法介紹


1.apply()說明

作用范圍:pandas中的SeriesDataFrame
作用:通過使用apply()方法,我們可以調用自己定義的函數,使得代碼結構更加清晰,簡潔。


2.apply()的應用過程

如果一個SeriesDataFrame調用apply()方法,然后使用自己定義的函數,其中自定義的函數的第一個參數,代表的是SeriesDataFrame的下一個“緯度”
比如說如果是DataFrame,則參數是他的每一個列。如果是Series,則是他的每一個值。

(1)DataFrame,參數是他的每一個列
eg:計算一個DataFrame各個字段的偏度和峰度

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'key1':[1, 2, 3, 4, 5],
    'key2':[4, 5, 6, 2, 1]
})

def skew_kurt(x):
    print(x, type(x))
    skews = x.skew()
    kurts = x.kurt()
    return pd.Series([skews, kurts], index=['skew', 'kurt']) # Series的參數為Series,則會變為DataFrame,且參數變為列
print(df.apply(skew_kurt))


# 結果:
0    1
1    2
2    3
3    4
4    5
Name: key1, dtype: int64 <class 'pandas.core.series.Series'>
0    1
1    2
2    3
3    4
4    5
Name: key1, dtype: int64 <class 'pandas.core.series.Series'>
0    4
1    5
2    6
3    2
4    1
Name: key2, dtype: int64 <class 'pandas.core.series.Series'>
      key1      key2
skew   0.0 -0.235514
kurt  -1.2 -1.963223

通過輸出結果中的可以看到,該函數會執行多次,且每次執行都會將DataFrame中的某一列傳過去。
(2)Series,參數是他的每一個值
eg:將一個Series的每一個值用該值的第一個字符替換

import pandas as pd
import numpy as np

s = pd.Series(['wang', 'li', 'zhao'])

def text(x):
    print(x, type(x))
    return x[0] # Series的參數為Series,則會變為DataFrame,且參數變為列
print(s.apply(text))

# 結果:
wang <class 'str'>
li <class 'str'>
zhao <class 'str'>
0    w
1    l
2    z
dtype: object

3.apply()應用

(1)通過上面的例子,我們可以看見其可以應用於SeriesDataFrame
(2)apply()方法還可以應用於分組---groupby()參數也是代表下一個緯度
eg:

import pandas as pd
import numpy as np

df = pd.DataFrame({'data1':np.random.rand(5),
                  'data2':np.random.rand(5),
                  'key1':list('aabba'),
                  'key2':['one','two','one','two','one']})

print(df.groupby('key1').apply(lambda x: x.describe()))

# 結果:
a    count  3.000000  3.000000
     mean   0.693046  0.608697
     std    0.257070  0.522231
     min    0.396401  0.011814
     25%    0.614231  0.422315
     50%    0.832060  0.832817
     75%    0.841368  0.907138
     max    0.850676  0.981459
b    count  2.000000  2.000000
     mean   0.352287  0.482039
     std    0.343271  0.675147
     min    0.109558  0.004638
     25%    0.230922  0.243339
     50%    0.352287  0.482039
     75%    0.473651  0.720740
     max    0.595016  0.959441

4.小結

  • 通過使用apply()方法,我們可以調用自己定義的函數,使得代碼結構更加清晰,簡潔。
  • 自定義的函數的第一個參數,代表的是下一個“緯度”


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM