Steps to Multiply Column Values by a Row
Below are the steps to multiply column values by a row:
- Dataframe: Create a dataFrame.
- Series: Create a row (series) for multiplication.
- Perform Multiplication: Perform element-wise multiplication using the mul method.
- Store Results: Place the calculated products in a new DataFrame or update the existing one.
Example 1: Basic Multiplication
import pandas as pd
# Create DataFrame
data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]}
df = pd.DataFrame(data)
# Create Row for Multiplication
row = pd.Series([10, 20, 30], index=['A', 'B', 'C'])
# Multiply Column by Row
result = df.mul(row, axis=1)
print("Original DataFrame:\n", df)
print("Row for Multiplication:\n", row)
print("Resulting DataFrame:\n", result)
# This code is contributed by Susobhan Akhuli
Output
Original DataFrame:
A B C
0 1 4 7
1 2 5 8
2 3 6 9
Row for Multiplication:
A 10
B 20
C 30
dtype: int64
Resulting DataFrame:
A B C
0 10 80 210
1 20 100 240
2 30 120 270
Example 2: Handling Missing Data
import pandas as pd
# Create DataFrame with Missing Values
data = {'A': [1, 2, None], 'B': [4, None, 6], 'C': [7, 8, 9]}
df = pd.DataFrame(data)
# Create Row for Multiplication
row = pd.Series([10, 20, 30], index=['A', 'B', 'C'])
# Multiply Column by Row and Fill Missing Values
result = df.mul(row, axis=1).fillna(0)
print("Original DataFrame with Missing Values:\n", df)
print("Row for Multiplication:\n", row)
print("Resulting DataFrame with Filled Missing Values:\n", result)
# This code is contributed by Susobhan Akhuli
Output
Original DataFrame with Missing Values:
A B C
0 1.0 4.0 7
1 2.0 NaN 8
2 NaN 6.0 9
Row for Multiplication:
A 10
B 20
C 30
dtype: int64
Resulting DataFrame with Filled Missing Values:
A B C
0 10.0 80.0 210
1 20.0 0.0 240
2 0.0 120.0 270
Multiply Each Value In A Column By A Row in Python Pandas
In Python Data Analysis and Manipulation, it’s often necessary to perform element-wise operations between rows and columns of DataFrames. This article focuses on multiplying values in a column by those in a row, a task achievable using Pandas, NumPy, or even basic Python list comprehension.