Python Dataframe aggregate/groupby columns to do calculation
Hi team,
Below myWACC() is calculated in a country. I would like to apply this calculation groupby its column such as TRBCEcoSectorName. below coding is show one country as output. Would how to make it output aggregate and grouping as column "TRBCEcoSectorName"? Wonder it is possible? Thanks in advance.
import asyncio
import pandas as pd
import numpy as np
from datetime import date
import plotly.express as px
import refinitiv.dataplatform.eikon as ek
import ipywidgets
from ipywidgets import *
from plotly.subplots import make_subplots
import plotly.graph_objects as go
# by using stane along Jupyter Note book
ek.set_app_key('DEFAULT_CODE_BOOK_APP_KEY')
def my_WACC():
start_date='07/01/2021'
scale='6'
curn='USD'
Rics = country_screen = 'SCREEN(U(IN(Equity(active,public,primary))/*UNV:Public*/), IN(TR.ExchangeCountryCode,"HK"), IN(TR.InstrumentTypeCode,"ADR","BDR","CEDEAR","CHINDR","DRC","EDR","FULLPAID","GDR","INDIDR","INTERDR","ORD","PDR"),TOP(TR.CompanyMarketCap, 5000, nnumber), CURN=USD)'
df_main,err=ek.get_data(Rics,
['TR.CompanyMarketCap',
'Zav(Avail(TR.TotalDebtOutstanding(Period=FI0),TR.TotalDebtOutstanding(Period=FY0)))',
'Zav(Avail(TR.TtlPreferredSharesOut(Period=FI0),TR.TtlPreferredSharesOut(Period=FY0)))',
'TR.WACCCostofEquity',
'TR.WACCCostofDebt',
'TR.WACCCostofPreferred',
'TR.ExchangeCountryCode',
'TR.TRBCEconomicSector'],
{'Sdate':start_date,'Scale':scale,'Curn':curn})
# rename the column label
df_main.set_axis(['Instrument',
'Company_MarketCap',
'Total_debt',
'Total_PS',
'WACC_CostOfEuity',
'WACC_CostOfDebt',
'WACC_CostOfPS',
'ExchangeCode',
'TRBCEcoSectorName'],axis=1, inplace=True)
df_main['weight_mkc_country']=df_main['Company_MarketCap']/df_main['Company_MarketCap'].sum()
df_main['weight_ttd_country']=df_main['Total_debt']/df_main['Total_debt'].sum()
df_main['weight_ps_country']=df_main['Total_PS']/df_main['Total_PS'].sum()
df_main['wavg_cost_equity_country'] = df_main['WACC_CostOfEuity']*df_main['weight_mkc_country']
df_main['wavg_cost_debt_country'] = df_main['WACC_CostOfDebt']*df_main['weight_ttd_country']
df_main['wavg_cost_ps_country'] = df_main['WACC_CostOfPS']*df_main['weight_ps_country']
total_capital = df_main['Company_MarketCap'].sum()+df_main['Total_debt'].sum()+df_main['Total_PS'].sum()
weight_MktCap = df_main['Company_MarketCap'].sum()/total_capital
weight_TtlDebt = df_main['Total_debt'].sum()/total_capital
weight_ps = df_main['Total_PS'].sum()/total_capital
display(df_main)
WACC_country = weight_MktCap*(df_main['wavg_cost_equity_country'].sum()/100) + weight_TtlDebt*(df_main['wavg_cost_debt_country'].sum()/100) + weight_ps*(df_main['wavg_cost_ps_country'].sum()/100)
return WACC_country
df = my_WACC()
df
Best Answer
-
I think what you're looking for is the groupby method of pandas. The documentation is available following the link below
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.groupby.html
But I suggest you start by reading the following user guide
https://pandas.pydata.org/docs/user_guide/groupby.html0
Answers
-
0
Categories
- All Categories
- 3 Polls
- 6 AHS
- 36 Alpha
- 166 App Studio
- 6 Block Chain
- 4 Bot Platform
- 18 Connected Risk APIs
- 47 Data Fusion
- 34 Data Model Discovery
- 685 Datastream
- 1.4K DSS
- 615 Eikon COM
- 5.2K Eikon Data APIs
- 10 Electronic Trading
- Generic FIX
- 7 Local Bank Node API
- 3 Trading API
- 2.9K Elektron
- 1.4K EMA
- 252 ETA
- 556 WebSocket API
- 38 FX Venues
- 14 FX Market Data
- 1 FX Post Trade
- 1 FX Trading - Matching
- 12 FX Trading – RFQ Maker
- 5 Intelligent Tagging
- 2 Legal One
- 23 Messenger Bot
- 3 Messenger Side by Side
- 9 ONESOURCE
- 7 Indirect Tax
- 60 Open Calais
- 275 Open PermID
- 44 Entity Search
- 2 Org ID
- 1 PAM
- PAM - Logging
- 6 Product Insight
- Project Tracking
- ProView
- ProView Internal
- 22 RDMS
- 1.9K Refinitiv Data Platform
- 650 Refinitiv Data Platform Libraries
- 4 LSEG Due Diligence
- LSEG Due Diligence Portal API
- 4 Refinitiv Due Dilligence Centre
- Rose's Space
- 1.2K Screening
- 18 Qual-ID API
- 13 Screening Deployed
- 23 Screening Online
- 12 World-Check Customer Risk Screener
- 1K World-Check One
- 46 World-Check One Zero Footprint
- 45 Side by Side Integration API
- 2 Test Space
- 3 Thomson One Smart
- 10 TR Knowledge Graph
- 151 Transactions
- 143 REDI API
- 1.8K TREP APIs
- 4 CAT
- 27 DACS Station
- 121 Open DACS
- 1.1K RFA
- 104 UPA
- 193 TREP Infrastructure
- 228 TRKD
- 917 TRTH
- 5 Velocity Analytics
- 9 Wealth Management Web Services
- 90 Workspace SDK
- 11 Element Framework
- 5 Grid
- 18 World-Check Data File
- 1 Yield Book Analytics
- 46 中文论坛