繁体   English   中英

Pandas.DataFrame:创建一个新列,使用当前df中的一列并在另一个df中查找一列,并进行计算

[英]Pandas.DataFrame: Create a new column, using one column from current df and by looking up one column in another df, with calculation

嗨,我是 python / Pandas 的新用户。 请帮助我处理 Pandas.DataFrame (也许还有应用方法)。 我有两个DataFrame,示例如下。 我想通过查找每个产品的单价乘以 df_products['Qty Sold'] 来创建一个新列 df_products['Sales Revenue']。 我该如何正确地做到这一点? 谢谢你。

# Pandas DataFrame example questions

import pandas as pd

products = ({
    'Product': ['A', 'B', 'C', 'D'],
    'Qty Sold': [10, 15, 22, 40]
})

prices =({
    'Product': ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
    'Unit Price': [3.20, 3.40, 2.20, 11.00, 8.05, 9.30, 4.00]
})

df_products = pd.DataFrame(product)

df_prices = pd.DataFrame(prices)

df_products

    **Product** **Qty Sold** **Sales Revenue**(to create) 
0      A             10            =10*3.20
1      B             15            =15*3.40
2      C             22            ........
3      D             40            ........

df_prices
     Product    Unit Price
0        A      3.20
1        B      3.40
2        C      2.20
3        D      11.00
4        E      8.05
5        F      9.30
6        G      4.00
df_products['Sales Revenue'] = df_products['Qty Sold'].mul(df_prices['Unit Price'])

df_merged = df_products.merge(df_prices, on = 'Product')

df_products['销售收入'] = df_merged['销售数量'] * df_merged['单价']

或者:

df_products['Sales Revenue'] = df_products.merge(df_prices, on = 'Product')['Qty Sold']*df_products.merge(df_prices, on = 'Product')['Unit Price']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM