Python中如何实现不同DataFrame的列相乘?
解决两个DataFrame按对应规则相乘的问题
你的问题根源是两个DataFrame的索引未对齐,pandas按索引匹配元素时,不匹配的位置会生成NaN。要实现Period与Month的顺序对应(20240201→Month0、20240301→Month1…),可以用以下两种方法:
方法1:对齐索引后相乘
先给Prices的Period按顺序生成对应的Month序号,再将两个DataFrame的索引统一为Month,即可直接相乘:
import pandas as pd # 重置Prices索引,生成序列列 prices_temp = Prices.reset_index() # 给每个Period分配对应Month序号(从0开始) prices_temp['Month'] = range(len(prices_temp)) # 将Month设为索引,与Table_ScenarioPercentages对齐 prices_temp = prices_temp.set_index('Month') # 执行相乘操作 adjusted_prices = prices_temp.iloc[:, 0] * Table_ScenarioPercentages.iloc[:, 0] # 可选:恢复原Period索引 adjusted_prices = adjusted_prices.reset_index()\ .merge(prices_temp.reset_index(), on='Month')\ .set_index('Period')\ .rename(columns={0: 'Adjusted_Price'})
方法2:直接按位置匹配相乘
如果两个DataFrame的目标列行顺序完全对应(Prices第1行对应Table第1行,以此类推),可以跳过索引对齐,直接取底层数值数组相乘:
# 提取列的数值数组进行运算 result_values = Prices.iloc[:, 0].values * Table_ScenarioPercentages.iloc[:, 0].values # 将结果转为与Prices结构一致的DataFrame adjusted_prices_df = pd.DataFrame( result_values, index=Prices.index, columns=['Adjusted_Price'] )
重要注意事项
- 若
Prices的Period未按时间排序,需先执行Prices = Prices.sort_index(),确保与Month序号对应正确 - 必须保证两个DataFrame的行数一致,否则会出现长度不匹配错误
内容的提问来源于stack exchange,提问作者Frank
相关产品推荐
相关产品推荐

