1. 程式人生 > 其它 >pandas中apply()函式的使用

pandas中apply()函式的使用

Pandas中apply()使用

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.apply.html

pandas.Series.apply 
Series.apply( func , convert_dtype = True , args = () , ** kwargs )[來源]
對 Series 的值呼叫函式。

可以是 ufunc(適用於整個系列的 NumPy 函式)或僅適用於單個值的 Python 函式。

引數
func函式
要應用的 Python 函式或 NumPy ufunc。

convert_dtype bool,預設為 True
嘗試為元素函式結果找到更好的 dtype。如果為 False,則保留為 dtype=object。請注意,dtype 始終保留用於某些擴充套件陣列 dtype,例如 Categorical。

args:tuple
在系列值之後傳遞給 func 的位置引數。

**kwargs
傳遞給 func 的其他關鍵字引數。

reyurn:
seties或DataFrame
如果 func 返回一個 Series 物件,則結果將是一個 DataFrame。

-----------------------
其他函式
Series.map
用於元素操作。
Series.agg
僅執行聚合型別操作。
Series.transform
只執行轉換型別操作。

針對series資料:

df['Extra'] = df.Nationality(欄位名).apply(lambda n, extra : extra if n == '漢' else 0, args=(5,))

針對DataFrame資料:

下面的示例對 x 和 y 列進行平方運算:

df.apply(lambda x : np.square(x) if x.name in ['x', 'y'] else x)
    x   y  z
a   1   4  3
b  16  25  6
c  49  64  9

下面的示例對第一行 (a 標籤所在行)進行平方運算:

df.apply(lambda x : np.square(x) if x.name == 'a' else x, axis=1)
預設情況下 axis=0 表示按列,axis=1 表示按行。

原文連結:https://blog.csdn.net/stone0823/article/details/100008619

備註:apply()可用於兩列日期的計算