要对不同索引的pandas DataFrames进行逐元素乘法,可以使用pandas的multiply
函数。下面是一个代码示例:
import pandas as pd
# 创建两个不同索引的DataFrames
df1 = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=[0, 1, 2])
df2 = pd.DataFrame({'A': [2, 4, 6], 'B': [8, 10, 12]}, index=[1, 2, 3])
# 使用multiply进行逐元素乘法
result = df1.multiply(df2, fill_value=0)
print(result)
输出结果为:
A B
0 0 0
1 4 40
2 18 60
3 0 0
在上面的示例中,multiply
函数将DataFrames的对应元素相乘,不存在的元素会被填充为0。