Pandas DataFrame apply() function is used to apply a function along an axis of the DataFrame. The function syntax is:
Pandas DataFrame apply()函数用于沿DataFrame的轴应用函数。 函数语法为:
def apply(
self,
func,
axis=0,
broadcast=None,
raw=False,
reduce=None,
result_type=None,
args=(),
**kwds
)
The important parameters are:
重要参数是:
- func: The function to apply to each row or column of the DataFrame. func :应用于DataFrame的每一行或每一列的函数。
- axis: axis along which the function is applied. The possible values are {0 or ‘index’, 1 or ‘columns’}, default 0. axis :沿其应用功能的轴。 可能的值为{0或'index',1或'columns'},默认值为0。
- args: The positional arguments to pass to the function. This is helpful when we have to pass additional arguments to the function. args :传递给函数的位置参数。 当我们必须将其他参数传递给函数时,这将很有帮助。
- kwargs: additional keyword arguments to pass to the function. This is helpful when we have to pass additional keyword arguments to the function. kwargs :传递给函数的其他关键字参数。 当我们必须将其他关键字参数传递给函数时,这将很有帮助。
熊猫DataFrame apply()示例 (Pandas DataFrame apply() Examples)
Let’s look at some examples of using apply() function on a DataFrame object.
让我们看一下在DataFrame对象上使用apply()函数的一些示例。
1.将函数应用于DataFrame元素 (1. Applying a Function to DataFrame Elements)
import pandas as pd
df = pd.DataFrame({'A': [1, 2], 'B': [10, 20]})
def square(x):
return x * x
df1 = df.apply(square)
print(df)
print(df1)
Output:
输出:
A B
0 1 10
1 2 20
A B
0 1 100
1 4 400
The DataFrame on which apply() function is called remains unchanged. The apply() function returns a new DataFrame object after applying the function to its elements.
调用apply()函数的DataFrame保持不变。 apply()函数在将函数应用于其元素之后返回一个新的DataFrame对象。
2.与lambda一起套用 (2. apply() with lambda)
If you look at the above example, our square() function is very simple. We can easily convert it into a lambda function. We can create a lambda function while calling the apply() function.
如果您看上面的示例,我们的square()函数非常简单。 我们可以轻松地将其转换为lambda函数。 我们可以在调用apply()函数的同时创建一个lambda函数。
df1 = df.apply(lambda x: x * x)
The output will remain the same as the last example.
输出将与上一个示例相同。
3.沿轴套用 (3. apply() along axis)
We can apply a function along the axis. But, in the last example, there is no use of the axis. The function is being applied to all the elements of the DataFrame.
我们可以沿轴应用一个函数。 但是,在最后一个示例中,没有使用轴。 该功能将应用于DataFrame的所有元素。
The use of axis becomes clear when we call an aggregate function on the DataFrame rows or columns. Let’s say we want to get the sum of elements along the columns or indexes. The output will be different based on the value of the axis argument.
当我们在DataFrame行或列上调用聚合函数时,可以清楚地使用轴。 假设我们要获取沿列或索引的元素之和。 根据axis参数的值,输出将有所不同。
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': [1, 2], 'B': [10, 20]})
df1 = df.apply(np.sum, axis=0)
print(df1)
df1 = df.apply(np.sum, axis=1)
print(df1)
Output:
输出:
A 3
B 30
dtype: int64
0 11
1 22
dtype: int64
In the first example, the sum of elements along the column is calculated. Whereas in the second example, the sum of the elements along the row is calculated.
在第一个示例中,计算沿列的元素总数。 而在第二个示例中,计算沿行的元素之和。
4. DataFrame apply()与参数 (4. DataFrame apply() with arguments)
Let’s say we want to apply a function that accepts more than one parameter. In that case, we can pass the additional parameters using the ‘args’ argument.
假设我们要应用一个接受多个参数的函数。 在这种情况下,我们可以使用'args'参数传递附加参数。
import pandas as pd
def sum(x, y, z):
return x + y + z
df = pd.DataFrame({'A': [1, 2], 'B': [10, 20]})
df1 = df.apply(sum, args=(1, 2))
print(df1)
Output:
输出:
A B
0 4 13
1 5 23
5.带有位置和关键字参数的DataFrame apply() (5. DataFrame apply() with positional and keyword arguments)
Let’s look at an example where we will use both ‘args’ and ‘kwargs’ parameters to pass positional and keyword arguments to the function.
让我们看一个示例,其中我们将同时使用'args'和'kwargs'参数来将位置参数和关键字参数传递给该函数。
import pandas as pd
def sum(x, y, z, m):
return (x + y + z) * m
df = pd.DataFrame({'A': [1, 2], 'B': [10, 20]})
df1 = df.apply(sum, args=(1, 2), m=10)
print(df1)
Output:
输出:
A B
0 40 130
1 50 230
DataFrame applymap()函数 (DataFrame applymap() function)
If you want to apply a function element-wise, you can use applymap() function. This function doesn’t have additional arguments. The function is applied to each of the element and the returned value is used to create the result DataFrame object.
如果要按元素应用函数,则可以使用applymap()函数。 此函数没有其他参数。 该函数将应用于每个元素,并且返回值用于创建结果DataFrame对象。
import pandas as pd
import math
df = pd.DataFrame({'A': [1, 4], 'B': [100, 400]})
df1 = df.applymap(math.sqrt)
print(df)
print(df1)
Output:
输出:
A B
0 1 100
1 4 400
A B
0 1.0 10.0
1 2.0 20.0
Let’s look at another example where we will use applymap() function to convert all the elements values to uppercase.
让我们看另一个例子,我们将使用applymap()函数将所有元素值转换为大写。
import pandas as pd
df = pd.DataFrame({'Name': ['Pankaj', 'Meghna'], 'Role': ['ceo', 'cto']})
df1 = df.applymap(str.upper)
print(df)
print(df1)
Output:
输出:
Name Role
0 Pankaj ceo
1 Meghna cto
Name Role
0 PANKAJ CEO
1 MEGHNA CTO
参考资料 (References)
翻译自: https://www.journaldev.com/33478/pandas-dataframe-apply-examples
Pandas的DataFrame apply() 函数允许沿行或列应用自定义函数,支持lambda表达式、参数传递和轴定向操作。通过实例展示了如何使用apply()改变DataFrame元素、使用lambda函数、按轴应用、传递参数以及结合位置和关键字参数的应用。
886

被折叠的 条评论
为什么被折叠?



