Python for Finance: Analyze Big Financial Data

(Elle) #1
Q2 -1.225155 0.918877 0.580972 -0.130118

Q3 0.465366 -0.212719 0.624617 -0.568196

In  [ 41 ]: groups.max()
Out[41]: No1 No2 No3 No4
Quarter
Q1 -0.155881 1.065173 1.037444 1.301174
Q2 -0.777546 1.730278 1.227124 0.979389
Q3 1.040318 -0.128799 1.565701 0.414084
In [ 42 ]: groups.size()
Out[42]: Quarter
Q1 3
Q2 3
Q3 3
dtype: int64

Grouping can also be done with multiple columns. To this end, we add another column,


indicating whether the month of the index date is odd or even:


In  [ 43 ]: df[‘Odd_Even’]  =   [‘Odd’, ‘Even’, ‘Odd’,  ‘Even’, ‘Odd’,  ‘Even’,
‘Odd’, ‘Even’, ‘Odd’]

This additional information can now be used for a grouping based on two columns


simultaneously:


In  [ 44 ]: groups  =   df.groupby([‘Quarter’,  ‘Odd_Even’])
In [ 45 ]: groups.size()
Out[45]: Quarter Odd_Even
Q1 Even 1
Odd 2
Q2 Even 2
Odd 1
Q3 Even 1
Odd 2
dtype: int64
In [ 46 ]: groups.mean()
Out[46]: No1 No2 No3 No4
Quarter Odd_Even
Q1 Even -0.788818 -0.985819 0.403796 -1.753784
Odd -0.446592 -0.343749 0.555425 0.450190
Q2 Even -0.955902 1.566050 0.822119 0.581734
Odd -1.763660 -0.375469 0.098678 -1.553824
Q3 Even -0.103058 -0.366170 -0.478036 -0.032810
Odd 0.749578 -0.135993 1.175944 -0.835890

This concludes the introduction into pandas and the use of DataFrame objects. Subsequent


sections apply this tool set to real-world financial data.

Free download pdf