apply()主要用在
Python: 如何對 pandas.DataFrame 兩欄位運算後,增加到最後一欄?
pandas官網對於apply()的說明
(點此或下圖連結官網):
DataFrame.apply(func, axis=0, raw=False, result_type=None, args=(), **kwargs)
主要參數是func跟axis
(若func的參數為df,通常 axis=1, 但預設值是0)
參考此篇:
Python: 如何對 pandas.DataFrame 兩欄位運算後,增加到最後一欄?
就知道為何axis=1
本篇則主要說明result_type
import pandas as pd
df = pd.DataFrame({‘A’: [1, 2, 3],
‘B’: [4, 5, 6],
‘C’: [7, 8, 9]})
“””df:
“””
# 將每一row的值乘上2,並返回一個純量(整row乘以2的總和)
# if axis=1
def func(x):
return (x * 2).sum()
# 1*2+4*2+7*2=24
# 2*2+5*2+8*2=30
# 3*2+6*2+9*2=36
# 使用 result_type=’broadcast’
result_broadcast = df.apply(func, axis=1, result_type=’broadcast’)
print(“result_broadcast:\n”,result_broadcast)
# 使用 result_type=’expand’
result_expand = df.apply(func, axis=1, result_type=’expand’)
print(“\nresult_expand:\n”,result_expand)
result_reduce = df.apply(func, axis=1, result_type=’reduce’)
print(“\nresult_reduce:\n”,result_reduce)
#此範例func返回純量,所以expand, reduce 看不出差別

輸出結果:

推薦hahow線上學習python: https://igrape.net/30afN







![Python: 使用 flat_list.extend( List[pandas.Series] ) 實現 pandas.DataFrame 列擴展教學 Python: 使用 flat_list.extend( List[pandas.Series] ) 實現 pandas.DataFrame 列擴展教學](https://i2.wp.com/savingking.com.tw/wp-content/uploads/2025/04/20250421141348_0_14cedf.png?quality=90&zoom=2&ssl=1&resize=350%2C233)
![Python:如何使用 PyMuPDF (import fitz ) 提取 PDF 文本區塊並存儲為 DataFrame ; text: List[ Tuple[float|str|int] ] = page.get_text(“blocks”) Python:如何使用 PyMuPDF (import fitz ) 提取 PDF 文本區塊並存儲為 DataFrame ; text: List[ Tuple[float|str|int] ] = page.get_text(“blocks”)](https://i2.wp.com/savingking.com.tw/wp-content/uploads/2025/03/20250320084417_0_7783bd.png?quality=90&zoom=2&ssl=1&resize=350%2C233)
![Python爬蟲:BeautifulSoup的 .find_all() 與 .find() 與 .select(‘標籤名[屬性名1=”屬性值1″][屬性名2=”屬性值2″]’) ; from bs4 import BeautifulSoup ; Live Server(可以預覽HTML的VS Code套件) Python爬蟲:BeautifulSoup的 .find_all() 與 .find() 與 .select(‘標籤名[屬性名1=”屬性值1″][屬性名2=”屬性值2″]’) ; from bs4 import BeautifulSoup ; Live Server(可以預覽HTML的VS Code套件)](https://i2.wp.com/savingking.com.tw/wp-content/uploads/2025/03/20250330190318_0_925655.jpg?quality=90&zoom=2&ssl=1&resize=350%2C233)
![Python: 如何使用 os.environ[“PATH”] 設定環境變數?與 sys.path.append() 差別為何? Python: 如何使用 os.environ[“PATH”] 設定環境變數?與 sys.path.append() 差別為何?](https://i0.wp.com/savingking.com.tw/wp-content/uploads/2024/09/20240905135312_0_890fa1.png?quality=90&zoom=2&ssl=1&resize=350%2C233)

近期留言