使用pandasapply()函数的详细指南

251 阅读2分钟

pandasapply()函数可以用来在pandas DataFrame的行或列中应用一个函数。

这个函数与其他函数不同,比如drop()replace(),后者提供了一个就地参数:

df.drop(['column1'], inplace=True)

df.rename({'old_column' : 'new_column'}, inplace=True)

apply()函数没有inplace参数,所以我们必须使用下面的语法来转换DataFrame的位置:

df = df.apply(lambda x: x*2)

下面的例子展示了如何在实践中使用这种语法,并使用以下pandas DataFrame:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19, 23, 25, 29],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
df

        points	assists	 rebounds
0	25	5	 11
1	12	7	 8
2	15	7	 10
3	14	9	 6
4	19	12	 6
5	23	9	 5
6	25	9	 9
7	29	4	 12

例子1:对一个列使用apply()原位转换

下面的代码展示了如何使用apply()对一个数据框架的列进行就地转换:

#multiply all values in 'points' column by 2 inplace
df.loc[:, 'points'] = df.points.apply(lambda x: x*2)

#view updated DataFrame
df

points	assists	rebounds
0	50	5	11
1	24	7	8
2	30	7	10
3	28	9	6
4	38	12	6
5	46	9	5
6	50	9	9
7	58	4	12

例2:对多列使用apply()原地转换

下面的代码显示了如何使用apply()对多个数据框架列进行原地转换:

multiply all values in 'points' and 'rebounds' column by 2 inplace
df[['points', 'rebounds']] = df[['points', 'rebounds']].apply(lambda x: x*2)

#view updated DataFrame
df

	points	assists	rebounds
0	50	5	22
1	24	7	16
2	30	7	20
3	28	9	12
4	38	12	12
5	46	9	10
6	50	9	18
7	58	4	24

例3:对所有列使用apply()原地转换

下面的代码显示了如何使用apply()对所有的数据框架列进行原地转换:

#multiply values in all columns by 2
df = df.apply(lambda x: x*2)

#view updated DataFrame
df

	points	assists	rebounds
0	50	10	22
1	24	14	16
2	30	14	20
3	28	18	12
4	38	24	12
5	46	18	10
6	50	18	18
7	58	8	24

其他资源

下面的教程介绍了如何在pandas中执行其他常见的函数:

如何在Pandas中计算列的总和
如何在Pandas中计算列的平均值
如何在Pandas中查找列的最大值