如何在 Pandas 中為單一列使用 apply() 函式?
我們可以使用 lambda 表示式對 DataFrame 的一列使用 apply() 函式。
步驟
建立一個可能存在不同的二維表格資料 df。
列印輸入 DataFrame df。
使用 apply() 方法用 lambda x: x*2 表示式替換列 x。
列印修改後的 DataFrame。
示例
import pandas as pd df = pd.DataFrame( { "x": [5, 2, 1, 5], "y": [4, 10, 5, 10], "z": [1, 1, 5, 1] } ) print "Input DataFrame is:
", df df['x'] = df['x'].apply(lambda x: x * 2) print "After applying multiplication of 2 DataFrame is:
", df
輸出
Input DataFrame is: x y z 0 5 4 1 1 2 10 1 2 1 5 5 3 5 10 1 After applying multiplication of 2 DataFrame is: x y z 0 10 4 1 1 4 10 1 2 2 5 5 3 10 10 1
廣告