📌  相关文章
📜  如何将函数应用于 Pandas 中的多个列?

📅  最后修改于: 2022-05-13 01:54:41.657000             🧑  作者: Mango

如何将函数应用于 Pandas 中的多个列?

让我们看看如何将函数应用于 Pandas DataFrame 中的多个列。要执行此任务将使用apply()函数。

pandas.DataFrame.apply

此函数沿 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)

输出 :