首页 > 解决方案 > 从导入的 excel 文件在 Python 中创建 sumproduct 和 groupby

问题描述

我有一个 excel 文件,其中包含有关其股票价格的数据。有 4 列股票代码、数据、价格和交易单位数量。我已经成功地在 Python 中导入了数据,现在我需要将价格乘以每个股票的单位数。excel 文件中有 10 类 TICKER 和 33900 个观测值。我需要在 Python 中编写一个函数,它将价格和每个日期和组的交易单位数量乘以代码值。到目前为止,我已经完成了:将 pandas 导入为 pd df = pd.read_excel (r'E:\Assignment\InputData_test1a_Py.xlsx', sheet_name='RawData') print (df)。请为此建议函数定义。 在此处输入图像描述

标签: pandasdataframe

解决方案


如果我正确理解您的要求,这应该可以解决您的问题:

# Generate a dataframe that is similar to yours
df = pd.DataFrame(
    {
        'Ticker':[f'Id{i}' for i in range(1,8,1)],
        'Date':['03-Jan-07'] * 7,
        'Prices':[95,989,110,125,160,240,333],
        'Close Units':[num / 10_000 for num in range(1,8,1)]
    }
)

# Assign new column Value, which is the product of Prices and Close Units
# groupby and sum
df_out = (
    df
    .assign(Value = df['Prices'] * df['Close Units'])
    .groupby(['Ticker','Date'])
    ['Value']
    .sum()
)

你应该得到 sumproduct groupbyTickerDate

                    Value
Ticker  Date    
Id1     03-Jan-07   0.0095
Id2     03-Jan-07   0.1978
Id3     03-Jan-07   0.0330
Id4     03-Jan-07   0.0500
Id5     03-Jan-07   0.0800
Id6     03-Jan-07   0.1440
Id7     03-Jan-07   0.2331


推荐阅读