pandas - 从导入的 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)。请为此建议函数定义。
解决方案
如果我正确理解您的要求,这应该可以解决您的问题:
# 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 groupbyTicker
和Date
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
推荐阅读
- android-studio - Gradle error with latest version of android studio
- excel - Excel: Sort cell base on specific text
- c++ - Why there is single exception type for web::json
- python - How to fix this condition?
- python-3.x - Is there way to change values in labels list from button list
- jasmine - Angular Routing Component Testing
- elasticsearch - kafka-connect-elasticsearch: How to sync elasticsearch with consumer group?
- reporting-services - SSRS Passing parameters to oracle DB Issue
- firebase - PHP- No option to authenticate user in firebase-php
- python - 对多个 Python Pandas 列求和,并带有一个条件