Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to apply functions element-wise in a dataframe in Python?
When working with Pandas DataFrames, you may need to apply functions element-wise to every cell. While many operations are vectorized, some custom functions require element-wise application. The applymap() method is designed for this purpose.
The applymap() method takes a single value as input and returns a single value as output, applying the function to every element in the DataFrame.
Syntax
DataFrame.applymap(func)
Basic Example
Here's how to use applymap() to multiply every element by a constant ?
import pandas as pd
import numpy as np
# Create a sample DataFrame
my_df = pd.DataFrame(np.random.randn(5,5), columns=['col_1','col_2','col_3', 'col_4', 'col_5'])
print("Original DataFrame:")
print(my_df)
# Apply function element-wise
result = my_df.applymap(lambda x: x * 11.45)
print("\nAfter applying multiplication by 11.45:")
print(result)
Original DataFrame:
col_1 col_2 col_3 col_4 col_5
0 -0.671510 -0.860741 0.886484 0.842158 2.182341
1 -1.355763 0.247240 -0.653630 -0.278095 0.163044
2 -0.816203 1.664006 1.555648 1.625890 -0.412338
3 -1.013273 -1.565076 1.297014 -0.303504 -1.623573
4 0.725949 -0.077588 -0.886957 0.433478 -0.300151
After applying multiplication by 11.45:
col_1 col_2 col_3 col_4 col_5
0 -7.689189 -9.855486 10.150241 9.642709 24.985803
1-15.523488 2.830898 -7.484022 -3.184189 1.866854
2 -9.345527 19.072869 17.762170 18.616436 -4.721270
3-11.601975-17.920120 14.830810 -3.485133-18.589962
4 8.282197 -0.888884-10.155677 4.963323 -3.436733
Custom Function Example
You can apply more complex functions to format or transform data ?
import pandas as pd
# Create a sample DataFrame with different data types
data = {'A': [1.234, 2.567, 3.891],
'B': [4.123, 5.678, 6.234],
'C': [7.456, 8.789, 9.123]}
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)
# Apply a function to round to 2 decimal places
rounded_df = df.applymap(lambda x: round(x, 2))
print("\nRounded to 2 decimal places:")
print(rounded_df)
Original DataFrame:
A B C
0 1.234 4.123 7.456
1 2.567 5.678 8.789
2 3.891 6.234 9.123
Rounded to 2 decimal places:
A B C
0 1.23 4.12 7.46
1 2.57 5.68 8.79
2 3.89 6.23 9.12
Type Conversion Example
Convert all numeric values to strings with formatting ?
import pandas as pd
# Create a numeric DataFrame
df = pd.DataFrame({'X': [10, 20, 30], 'Y': [40, 50, 60]})
print("Original DataFrame:")
print(df)
print("Data types:")
print(df.dtypes)
# Convert all values to formatted strings
string_df = df.applymap(lambda x: f"Value: {x}")
print("\nConverted to formatted strings:")
print(string_df)
print("Data types after conversion:")
print(string_df.dtypes)
Original DataFrame:
X Y
0 10 40
1 20 50
2 30 60
Data types:
X int64
Y int64
dtype: object
Converted to formatted strings:
X Y
0 Value: 10 Value: 40
1 Value: 20 Value: 50
2 Value: 30 Value: 60
Data types after conversion:
X object
Y object
dtype: object
Key Points
-
applymap()works on every individual element of the DataFrame - The function must accept a single value and return a single value
- Use lambda functions for simple operations or define custom functions for complex logic
- For operations on rows or columns, use
apply()instead - For simple mathematical operations, vectorized operations are usually faster
Conclusion
The applymap() method is essential for element-wise transformations in DataFrames. Use it when you need to apply custom functions to every cell, especially for formatting, type conversion, or complex mathematical operations that can't be vectorized.
