如何将函数应用到 pandas dataframe 中的某一列中去
在 pandas 中,可以使用 apply()
和 transform()
等方法对列和 dataframe 进行转换和操作。所需的转换作为参数以函数的形式传递给这些方法。每种方法都有其细微的区别和作用。本文将介绍如何将一个函数应用于一列或整个 dataframe。
pandas apply()
和 transform()
方法
apply()
和 transform()
方法都是对单个列和整个 dataframe 进行操作。apply()
方法沿着指定的轴应用函数。它将列作为 dataframe 传递给自定义函数,而 transform()
方法将单个列作为 pandas series
传递给自定义函数。
apply()
方法的输出根据输入以 dataframe
或 series
的形式接收,而 transform()
方法则以 series
的形式接收。apply()
和 transform()
方法的语法都类似于:
dataframe.apply(customfunction, axis=0)
dataframe.transform(customfunction, axis=0)
参数对应于
customfunction
:要应用于 dataframe 或series
的函数。axis
:0 指的是行,1 指的是列,函数需要应用在行或列上。
使用 apply()
将函数应用于 pandas dataframe 列
现在我们已经掌握了基础知识,让我们动手编写代码,了解如何使用 apply()
方法将一个函数应用到 dataframe 列。
我们将使用下面的 dataframe 示例。
import pandas as pd
import numpy as np
df = pd.dataframe([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["a", "b", "c"])
print(df)
将函数应用到整个 dataframe 的示例代码如下所示。
import pandas as pd
import numpy as np
df = pd.dataframe([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["a", "b", "c"])
print(df)
def add_2(x):
return x 2
df = df.apply(add_2)
print(df)
输出:
a b c
0 1 2 3
1 4 5 6
2 7 8 9
a b c
0 3 4 5
1 6 7 8
2 9 10 11
如上图所示,函数可以应用于整个 dataframe。
将函数应用于单列
让我们来看看当函数沿单列应用时会发生什么。
import pandas as pd
import numpy as np
df = pd.dataframe([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["a", "b", "c"])
print(df)
def add_2(x):
return x 2
df["a"] = df["a"].apply(add_2)
print(df)
# or #
df["a"].transform(add_2)
print(df)
输出:
a b c
0 1 2 3
1 4 5 6
2 7 8 9
a b c
0 3 2 3
1 6 5 6
2 9 8 9
使用 transform()
将一个函数应用到 pandas dataframe 列
让我们看看如何使用 transform()
方法将一个函数应用到一个 dataframe 列。我们将使用与上面相同的 dataframe 示例。
应用函数到整个 dataframe 的示例代码如下所示。
import pandas as pd
import numpy as np
df = pd.dataframe([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["a", "b", "c"])
print(df)
def add_2(x):
return x 2
df = df.transform(add_2)
print(df)
输出:
a b c
0 1 2 3
1 4 5 6
2 7 8 9
a b c
0 3 4 5
1 6 7 8
2 9 10 11
如上图所示,函数可以应用到整个 dataframe。
将函数应用于单列
让我们来看看当函数沿单列应用时会发生什么。
import pandas as pd
import numpy as np
df = pd.dataframe([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=["a", "b", "c"])
print(df)
def add_2(x):
return x 2
df["a"] = df["a"].transform(add_2)
print(df)
输出:
a b c
0 1 2 3
1 4 5 6
2 7 8 9
a b c
0 3 2 3
1 6 5 6
2 9 8 9
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
pandas dataframe dataframe.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:python
-
dataframe.shift() 函数是将 dataframe 的索引按指定的周期数进行移位。
python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:python
-
python pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:python
-
pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 dataframe 中。
pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:python
-
本教程介绍了如何在 pandas 中使用 dataframe.merge()方法合并两个 dataframes。
pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:python
-
本教程介绍了如何使用 python 中的 loc 和 iloc 从 pandas dataframe 中过滤数据。
在 python 中将 pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:python
-
了解如何在 python 中将 pandas 系列日期时间转换为字符串