python - 通过将不同数据帧中具有相同索引的两列相乘来添加新列

标签 python pandas

我有两个索引数据框:

总数据

                       quantity
customer brand product
      C1    B1      P1      100
      C1    B1      P2       10
      C1    B2      P3       50
      C2    B1      P1       75
      C2    B2      P3        5

和产品:

                 price
brand product
   B1      P1        5
   B1      P2       20
   B2      P3        7

当我打印total_data.quantity * products.price时,我得到:

                       quantity
customer brand product
      C1    B1      P1      500
      C1    B1      P2      200
      C1    B2      P3      350
      C2    B1      P1      375
      C2    B2      P3       35

但我想将此列分配给 total_data 于是,我尝试了两种方法:

总数据['收入'] = 总数据.数量 * 产品.价格

total_data.assign(收入=total_data.quantity * products.price)

但在这两种情况下,我都在 venue 列中得到了 NaN 值。

有解决办法吗?

最佳答案

这里我将如何组合数据:

df = total_data.merge(products, 'left') 
df['income'] = df['quantity'] * df['price']  

输出:

  customer brand product  quantity  price        income
0       C1    B1      P1       100      5           500
1       C1    B1      P2        10     20           200
2       C1    B2      P3        50      7           350
3       C2    B1      P1        75      5           375
4       C2    B2      P3         5      7            35

 total_data['income'] = total_data['quantity'] * total_data.merge(products, 'left')['price']

对于:

  customer brand product  quantity  income
0       C1    B1      P1       100     500
1       C1    B1      P2        10     200
2       C1    B2      P3        50     350
3       C2    B1      P1        75     375
4       C2    B2      P3         5      35

关于python - 通过将不同数据帧中具有相同索引的两列相乘来添加新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59316295/

相关文章:

python - 在 Pandas 数据框中附加日期时间行和转发填充数据

python - 从 xml 中删除签名

python - CSS 未在 CGI 脚本中应用

python - 添加 future 日期以绘制趋势线

python - Python 3 中的排序函数

python - 如何根据其他列中的多个条件更新列数据?

python-3.x - ValueError : Expected 2D array, 得到的是一维数组。 Python 线性回归函数

indexing - 使用 ix() 方法对带有负索引的 Pandas DataFrame 进行切片

python - 属性错误 : 'DataFrame' object has no attribute 'label'

python - 混淆矩阵颜色匹配数据大小而不是分类精度