python pandas中apply()方法用法汇总

apply 函数是 pandas 中用于对 DataFrame 或 Series 中的每一行或每一列应用一个函数的强大工具。在apply()方法中,通常会传入一个函数作为参数,这个函数会应用到DataFrame的每一行或每一列上,或Series的每个元素上。

下面是一些常见的用法示例:

1. 对 Series 使用 apply(),传入一个函数

如果你想对某一列(Series)应用函数,可以直接调用 apply 方法。

import pandas as pd

# 创建一个示例 DataFrame
data = {
    'A': [1, 2, 3, 4, 5]
}
df = pd.DataFrame(data)

# 使用 apply 对列 A 中的每个值进行操作
df['B'] = df['A'].apply(lambda x: x ** 2)  # 将每个值平方

print(df)

2. 对 DataFrame 使用 apply()

可以对 DataFrame 的行或列使用 apply(),这里使用 axis 参数来选择是按行操作 (axis=1) 还是按列操作 (axis=0,默认值)。

  • 按列操作(默认)
# 对每列使用apply,计算列的和
column_sums = df.apply(lambda x: x.sum(), axis=0)
print("每列的和:")
print(column_sums)
  • 按行操作
# 对每行使用apply,计算行的和
row_sums = df.apply(lambda x: x.sum(), axis=1)
print("\n每行的和:")
print(row_sums)

3. 使用自定义函数

你可以定义一个更复杂的函数,然后使用 apply 来应用它。

def custom_function(x):
    return x + 10

df['C'] = df['A'].apply(custom_function)
print(df)

4. 多列操作

如果需要对多列进行操作,可以使用 applyaxis=1 来按行操作,并可以访问多列的值。

data = {
    'A': [1, 2, 3],
    'B': [10, 20, 30]
}
df = pd.DataFrame(data)

# 定义一个函数,接收一行的 Series,并访问一行里的多列
def combine_values(row):
    return row['A'] + row['B']

# 应用函数并创建新列
df['C'] = df.apply(combine_values, axis=1)
print(df)

5. 处理缺失值

使用 apply 也可以在处理缺失值时提供灵活性。

data = {
    'A': [1, 2, None, 4],
    'B': [10, None, 30, 40]
}
df = pd.DataFrame(data)

# 定义处理缺失值的函数
def fill_missing(row):
    return row.fillna(0)

# 应用函数
df = df.apply(fill_missing, axis=1)
print(df)

6. apply() 中传入多个参数

希望 apply() 中的函数使用多个参数,可以在函数定义中使用额外的参数,并通过 apply() 传递它们。

# 定义一个带有额外参数的函数
def multiply(x, factor):
    return x * factor

# 创建一个Series
s = pd.Series([1, 2, 3, 4, 5])

# 使用apply并传递额外的参数, multiply函数的参数 放在apply()的参数中,factor就是传入multiply函数的参数
factor = 10
s_result = s.apply(multiply, factor=factor)

print(s_result)

总结

  • apply() 方法的参数通常是一个函数,可以是简单的 lambda 函数,也可以是定义好的函数。
  • 如果是对 Series 使用 apply(),函数会作用于每个元素。
  • 如果是对 DataFrame 使用 apply(),可以通过 axis 参数选择按行操作 (axis=1) 还是按列操作 (axis=0)。
  • 在自定义函数中,你可以通过额外的参数传递额外的信息。

apply 函数非常灵活,能够满足多种需求。可以通过简单的函数、复杂的逻辑,甚至是处理缺失值等方式来操作 DataFrame 或 Series。根据具体的需求选择适合的用法即可!

你可能感兴趣的:(python进阶,python,pandas,数据分析)