请求协助:将基于NumPy数组的计算迁移至Pandas DataFrame
用Pandas DataFrame复现NumPy数组计算逻辑
原NumPy代码逻辑说明
原代码实现了以下计算流程:
matrix_data是5×5×5的三维数组,维度对应(year, state, feature)(year/state/feature编号均为0-4)customers是3×5的二维数组,每行代表一个客户:数组中对应客户state的位置填充amount值,其余位置为0- 提取
matrix_data中指定年份(years)的层,得到3×5×5的子数组 - 将
customers扩展为3×5×1的三维数组,与提取的子数组逐元素相乘 - 沿
state维度(axis=1)求和,最终得到3×5的结果,每行对应一个客户的各feature汇总值
用customer_data DataFrame复现步骤
1. 从DataFrame构建客户状态-金额数组
把customer_data中的state和amount转换成与原customers结构一致的数组(假设state是1-based编号,需转成0-based索引对应数组列):
import pandas as pd import numpy as np # 保留原matrix_data定义 matrix_data = np.arange(125).reshape(5,5,5) # 用户的customer_data DataFrame customer_data = pd.DataFrame({ "cust_id": ['x111', 'x222', 'x333'], "state": [2,3,2], "amount": [1,2,5], "year":[2 ,3, 4] }) # 构建客户状态-金额数组 num_states = 5 customers_array = np.zeros((len(customer_data), num_states)) # 向量化操作填充值(避免循环) state_indices = customer_data['state'] - 1 # 1-based转0-based索引 customers_array[np.arange(len(customer_data)), state_indices] = customer_data['amount'].values
2. 提取对应年份的matrix_data层
直接从`customerGame store Buildings-links的 Wide侧子几IA施舍veryJW**,不对,直接提取:
selected_years = customer_data['year'].values matrix_selected = matrix_data[selected_years]
3. 执行核心计算
和原NumPy代码逻辑完全一致:
# 扩展维度以匹配matrix_selected的形状 customers_expanded = customers_array[:, :, None] # 逐元素相乘后沿state维度求和 result = (customers_expanded * matrix_selected).sum(axis=1)
可选:将结果关联回原DataFrame
如果需要把计算结果和客户信息绑定,可以合并成新的DataFrame:
# 将结果转为DataFrame,命名feature列 result_df = pd.DataFrame(result, columns=[f'feature_{i}' for i in range(5)]) # 和原数据合并 final_df = pd.concat([customer_data, result_df], axis=1)
结果验证
生成的customers_array与原customers数组完全一致,selected_years也和原years参数匹配,因此最终result与原代码的计算结果完全相同。
内容的提问来源于stack exchange,提问作者user1000x
相关产品推荐
相关产品推荐

