何時使用 Pandas `map`、`applymap` 或 `apply`?
在 Pandas 中選擇 map、applymap 和 apply
使用 Pandas DataFrame 時,通常需要對資料應用函數以各種方式。向量化常用的三種方法是map、applymap和apply。每個都有其獨特的用途和應用。
Map
map 是特定於 Series 物件的方法,它將函數應用於 Series 中的每個元素。它需要一個接受單一值作為輸入並傳回單一值的函數。
範例:
import pandas as pd # Create a Series series = pd.Series([1, 2, 3, 4, 5]) # Apply a function to each element def square(x): return x**2 # Apply the function to the series using map squared_series = series.map(square) print(squared_series)
輸出:
0 1 1 4 2 9 3 16 4 25 dtype: int64
Applymap
ApplymapApplymap# Create a DataFrame df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]}) # Apply a function to each element of the DataFrame def format_number(x): return "{:.2f}".format(x) # Apply the function to the DataFrame using applymap formatted_df = df.applymap(format_number) print(formatted_df)範例
a b 0 1.00 4.00 1 2.00 5.00 2 3.00 6.00
輸出:
申請適用
# Apply a function to each row of the DataFrame def get_max_min_diff(row): return row.max() - row.min() max_min_diff = df.apply(get_max_min_diff, axis=1) print(max_min_diff)
範例:
- 輸出:
- 用法摘要
- map:依元素函數套用到Series
以上是何時使用 Pandas `map`、`applymap` 或 `apply`?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

使用FiddlerEverywhere進行中間人讀取時如何避免被檢測到當你使用FiddlerEverywhere...

如何在10小時內教計算機小白編程基礎?如果你只有10個小時來教計算機小白一些編程知識,你會選擇教些什麼�...

攻克Investing.com的反爬蟲策略許多人嘗試爬取Investing.com(https://cn.investing.com/news/latest-news)的新聞數據時,常常�...

Python3.6環境下加載pickle文件報錯:ModuleNotFoundError:Nomodulenamed...

使用Scapy爬蟲時管道文件無法寫入的原因探討在學習和使用Scapy爬蟲進行數據持久化存儲時,可能會遇到管道文�...
