Pandas:如何同时使用Apply和Lambda

94 阅读2分钟

你可以使用下面的基本语法将lambda函数应用于pandas DataFrame。

df['col'] = df['col'].apply(lambda x: 'value1' if x < 20 else 'value2')

下面的例子展示了如何通过以下pandas DataFrame实际使用这种语法。

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                   'points': [18, 22, 19, 14, 14, 11, 20, 28],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4]})

#view DataFrame
print(df)

  team  points  assists
0    A      18        5
1    B      22        7
2    C      19        7
3    D      14        9
4    E      14       12
5    F      11        9
6    G      20        9
7    H      28        4

例1:使用Apply和Lambda创建新列

下面的代码展示了如何使用applylambda来创建一个新的列,其值取决于现有列的值。

#create new column called 'status'
df['status'] = df['points'].apply(lambda x: 'Bad' if x < 20 else 'Good')

#view updated DataFrame
print(df)

  team  points  assists status
0    A      18        5    Bad
1    B      22        7   Good
2    C      19        7    Bad
3    D      14        9    Bad
4    E      14       12    Bad
5    F      11        9    Bad
6    G      20        9   Good
7    H      28        4   Good

在这个例子中,我们创建了一个名为status的新列,它的值如下。

  • 如果积分列中的值小于20,则为''。
  • 如果积分列中的值大于或等于20,则为''。

例2:使用Apply和Lambda来修改现有的列

下面的代码展示了如何使用applylambda来修改DataFrame中的现有列。

#modify existing 'points' column
df['points'] = df['points'].apply(lambda x: x/2 if x < 20 else x*2)

#view updated DataFrame
print(df)

  team  points  assists
0    A     9.0        5
1    B    44.0        7
2    C     9.5        7
3    D     7.0        9
4    E     7.0       12
5    F     5.5        9
6    G    40.0        9
7    H    56.0        4

在这个例子中,我们通过在lambda函数中使用以下规则来修改现有点数列中的值。

  • 如果数值小于20,就用数值除以2。
  • 如果该值大于或等于20,则将该值乘以2。

使用这个lambda函数,我们能够修改现有积分栏中的数值。

其他资源

下面的教程解释了如何在pandas中执行其他常用函数:

如何将函数应用于Pandas Groupby
如何用Pandas中另一列的值填充NaN