深度阅读

How to apply a function to each element or column of a pandas DataFrame?

作者
作者
2023年08月22日
更新时间
15.03 分钟
阅读时间
0
阅读量

To apply a function to each element or column of a pandas DataFrame, you can use the apply() method. Here’s an example of applying a function to each element of a DataFrame:

import pandas as pd

# Define a function to multiply a number by 2
def multiply_by_2(x):
    return x * 2

# Create a DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# Apply the function to each element of the DataFrame
result = df.applymap(multiply_by_2)

print(result)

This will output:

   A   B
0  2   8
1  4  10
2  6  12

In the example above, we created a DataFrame and applied the multiply_by_2 function to each element of the DataFrame using the applymap() method. This method applies a function to every element of the DataFrame.

To apply a function to each column of a DataFrame, you can use the apply() method. Here’s an example:

import pandas as pd

# Define a function to calculate the sum of a Series
def sum_series(series):
    return series.sum()

# Create a DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# Apply the function to each column of the DataFrame
result = df.apply(sum_series)

print(result)

This will output:

A     6
B    15
dtype: int64

In the example above, we created a DataFrame and applied the sum_series function to each column of the DataFrame using the apply() method. This method applies a function to every column of the DataFrame.

I hope this helps! Let me know if you have any other questions.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。