如何将函数应用于 Pandas 中的多个列?
让我们看看如何将函数应用于 Pandas DataFrame 中的多个列。要执行此任务将使用apply()函数。
pandas.DataFrame.apply
此函数沿 DataFrame 的轴应用函数。
Syntax : DataFrame.apply(parameters)
Parameters :
- func : Function to apply to each column or row.
- axis : Axis along which the function is applied
- raw : Determines if row or column is passed as a Series or ndarray object.
- result_type : ‘expand’, ‘reduce’, ‘broadcast’, None; default None
- args : Positional arguments to pass to func in addition to the array/series.
- **kwds : Additional keyword arguments to pass as keywords arguments to func.
Returns : Series or DataFrame
示例 1:在两列中的每个元素之前添加“Geek”。
Python3
# import the module
import pandas as pd
# creating a DataFrame
df = pd.DataFrame({'String 1' :['Tom', 'Nick', 'Krish', 'Jack'],
'String 2' :['Jane', 'John', 'Doe', 'Mohan']})
# displaying the DataFrame
display(df)
# function for prepending 'Geek'
def prepend_geek(name):
return 'Geek ' + name
# executing the function
df[["String 1", "String 2"]] = df[["String 1", "String 2"]].apply(prepend_geek)
# displaying the DataFrame
display(df)
Python3
# import the module
import pandas as pd
# creating a DataFrame
df = pd.DataFrame({'Integers' :[1, 2, 3, 4, 5],
'Float' :[1.1, 2.2, 3.3, 4.4 ,5.5]})
# displaying the DataFrame
display(df)
# function for prepending 'Geek'
def multiply_by_2(number):
return 2 * number
# executing the function
df[["Integers", "Float"]] = df[["Integers", "Float"]].apply(multiply_by_2)
# displaying the DataFrame
display(df)
输出 :
示例 2:将每个元素的值乘以 2
Python3
# import the module
import pandas as pd
# creating a DataFrame
df = pd.DataFrame({'Integers' :[1, 2, 3, 4, 5],
'Float' :[1.1, 2.2, 3.3, 4.4 ,5.5]})
# displaying the DataFrame
display(df)
# function for prepending 'Geek'
def multiply_by_2(number):
return 2 * number
# executing the function
df[["Integers", "Float"]] = df[["Integers", "Float"]].apply(multiply_by_2)
# displaying the DataFrame
display(df)
输出 :