日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python?pandas中apply函數簡介以及用法詳解_python

作者:獨影月下酌酒 ? 更新時間: 2022-11-03 編程語言

1.基本信息

? Pandas 的 apply() 方法是用來調用一個函數(Python method),讓此函數對數據對象進行批量處理。Pandas 的很多對象都可以使用 apply() 來調用函數,如 Dataframe、Series、分組對象、各種時間序列等。

2.語法結構

? apply() 使用時,通常放入一個 lambda 函數表達式、或一個函數作為操作運算,官方上給出DataFrame的 apply() 用法:

DataFrame.apply(self, func, axis=0, raw=False, result_type=None, args=(), **kwargs)

參數:

  • func:函數或 lambda 表達式,應用于每行或者每列
  • axis:{0 or ‘index’, 1 or ‘columns’}, 默認為0
    • 0 or ‘index’: 表示函數處理的是每一列
    • 1 or ‘columns’: 表示函數處理的是每一行
  • raw:bool 類型,默認為 False;
    • False ,表示把每一行或列作為 Series 傳入函數中;
    • True,表示接受的是 ndarray 數據類型;
  • result_type:{‘expand’, ‘reduce’, ‘broadcast’, None}, default None
    These only act when axis=1 (columns):
    • ‘expand’ : 列表式的結果將被轉化為列。
    • ‘reduce’ : 如果可能的話,返回一個 Series,而不是展開類似列表的結果。這與 expand 相反。
    • ‘broadcast’ : 結果將被廣播到 DataFrame 的原始形狀,原始索引和列將被保留。
  • args: func 的位置參數
  • **kwargs:要作為關鍵字參數傳遞給 func 的其他關鍵字參數,1.3.0 開始支持

返回值:

  • Series 或者 DataFrame:沿數據的給定軸應用 func 的結果
	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``). 
	傳遞給函數的對象是Series對象,其索引是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.
	默認情況下( result_type=None),最終的返回類型是從應用函數的返回類型推斷出來的。否則,它取決于' result_type '參數。

注:DataFrame與Series的區別與聯系:

區別:

  • series,只是一個一維結構,它由index和value組成。
  • dataframe,是一個二維結構,除了擁有index和value之外,還擁有column。

聯系:

  • dataframe由多個series組成,無論是行還是列,單獨拆分出來都是一個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通用函數 (如 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
'''

# 在每行上返回類似列表的內容
df.apply(lambda x: [1, 2], axis=1)
'''
0    [1, 2]
1    [1, 2]
2    [1, 2]
dtype: object
'''

# result_type='expand' 將類似列表的結果擴展到數據的列
df.apply(lambda x: [1, 2], axis=1, result_type='expand')

'''
   0  1
0  1  2
1  1  2
2  1  2
'''

# 在函數中返回一個序列,生成的列名將是序列索引。
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' 將確保函數返回相同的形狀結果
# 無論是 list-like 還是 scalar,并沿軸進行廣播
# 生成的列名將是原始列名。
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

# 對各列應用函數 axis=0
df.apply(lambda x: np.sum(x))
A     6
B    15
C    24
dtype: int64

# 對各行應用函數
df.apply(lambda x: np.sum(x), axis=1)
a    12
b    15
c    18
dtype: int64

3.2 Series使用apply

官網案例

s = pd.Series([20, 21, 12],index=['London', 'New York', 'Helsinki'])
s
'''
London      20
New York    21
Helsinki    12
dtype: int64
'''

# 定義函數并將其作為參數傳遞給 apply,求值平方化。
def square(x):
     return x ** 2

s.apply(square)
'''
London      400
New York    441
Helsinki    144
dtype: int64
'''

# 通過將匿名函數作為參數傳遞給 apply
s.apply(lambda x: x ** 2)
'''
London      400
New York    441
Helsinki    144
dtype: int64
'''

# 定義一個需要附加位置參數的自定義函數
# 并使用args關鍵字傳遞這些附加參數。
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
'''

# 定義一個接受關鍵字參數并將這些參數傳遞
# 給 apply 的自定義函數。
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庫中的函數
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)
# 設置value的顯示長度為100,默認為50
pd.set_option('max_colwidth', 100)
# 用來計算日期差的包
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.總結

1.apply方法都是通過傳入一個函數或者lambda表達式對數據進行批量處理

2.apply方法處理的都是一個Series對象

參考鏈接:

1.https://blog.csdn.net/missyougoon/article/details/83301712

2.https://blog.csdn.net/qq_19528953/article/details/79348929

原文鏈接:https://blog.csdn.net/weixin_44852067/article/details/122364306

欄目分類
最近更新