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 list[] dictionary{key: value},如何從兩個list,建立一個dictionary? Python list[] dictionary{key: value},如何從兩個list,建立一個dictionary?](https://i2.wp.com/savingking.com.tw/wp-content/uploads/2022/09/20220904074100_2.png?quality=90&zoom=2&ssl=1&resize=350%2C233)


![Python: 資料格式如 List[dict],如何快速將SN加入每一個dict中,以利Excel輸出?如何解包dict? **dict ; 將List[dict]的資料轉為pandas.DataFrame 長什麼樣子? Python: 資料格式如 List[dict],如何快速將SN加入每一個dict中,以利Excel輸出?如何解包dict? **dict ; 將List[dict]的資料轉為pandas.DataFrame 長什麼樣子?](https://i2.wp.com/savingking.com.tw/wp-content/uploads/2024/02/20240208093926_0.png?quality=90&zoom=2&ssl=1&resize=350%2C233)
]*>.*?底下插入一個圖檔.*?</w:p>’, flags = re.DOTALL) ; new_xml, n = pattern.subn(”, xml, count=1)' title='Python正則替換:全面掌握 re.sub 與 re.subn 的差異與實戰 #substitute(替換); . 預設匹配「除\n以外的任意單一字元」; pattern = re.compile(r'<w:p[^>]*>.*?底下插入一個圖檔.*?</w:p>’, flags = re.DOTALL) ; new_xml, n = pattern.subn(”, xml, count=1)' loading='lazy' width=350 height=233 />
近期留言