我有两个索引数据帧:
总数据
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['income'] = total_data.quantity * products.price
和
total_data.assign(income = total_data.quantity * products.price)
但是在两种情况下,我在NaN
列中都得到了income
值。
有解决方案吗?
答案 0 :(得分:1)
这是我将如何合并数据的方法:
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