以下是我的数据框。它有多个股票。我试图从这些数据中找出两件事。
1)如何找到所有股票的最小/最大相对波动率的日期。这意味着具有相应日期的每只股票的最大和最小相对波动率。
Stock Date relativevolatility
0 AA.csv 2012-12-31 0.024419
1 AA.csv 2012-12-28 0.012888
2 AA.csv 2012-12-27 0.026482
3 AA.csv 2012-12-26 0.018423
4 AA.csv 2012-12-24 0.013994
5 AA.csv 2012-12-21 0.017422
6 AA.csv 2012-12-20 0.011541
7 AA.csv 2012-12-19 0.026316
8 AA.csv 2012-12-18 0.018120
9 AA.csv 2012-12-17 0.019406
10 AA.csv 2012-12-14 0.018454
11 AA.csv 2012-12-13 0.017411
12 AA.csv 2012-12-12 0.012673
13 AA.csv 2012-12-11 0.019699
14 AA.csv 2012-12-10 0.016442
15 AA.csv 2012-12-07 0.016403
16 AA.csv 2012-12-06 0.014011
17 AA.csv 2012-12-05 0.022340
18 AA.csv 2012-12-04 0.016677
19 AA.csv 2012-12-03 0.011862
20 AA.csv 2012-11-30 0.015458
21 AA.csv 2012-11-29 0.017794
22 AA.csv 2012-11-28 0.030102
23 AA.csv 2012-11-27 0.016888
24 AA.csv 2012-11-26 0.012019
25 AA.csv 2012-11-23 0.010791
26 AA.csv 2012-11-21 0.012092
27 AA.csv 2012-11-20 0.020544
28 AA.csv 2012-11-19 0.016857
29 AA.csv 2012-11-16 0.027044
... ... ...
70666 ZION.csv 2012-02-15 0.018929
70667 ZION.csv 2012-02-14 0.016287
尝试#1 df2.groupby(['日期''库存'])[' relativevolatility&#39]。。总和()idxmax()
这给了我一个时间/股票,但只有一个股票,我不确定我甚至得到该股票的最大相对波动率。
尝试#2 new.groupby([' Stock'])[' relativevolatility']。agg([pd.np.min,pd.np.max])
这给了我所有股票的最小值/最大值,但我无法弄清楚如何为每只股票的最小值和最大值添加一列。
如何打印一张表格,其中列出了所有股票的最小/最大相对波动率以及股票的最小值/最大值发生日期?
如何找到平均相对波动率,但是对于所有股票,每周的每一天都是如此?
答案 0 :(得分:0)
#if necessary
#df['Date'] = pd.to_datetime(df['Date'])
df1 = df.loc[df.groupby('Stock')['relativevolatility'].idxmin()].set_index('Stock')
df2 = df.loc[df.groupby('Stock')['relativevolatility'].idxmax()].set_index('Stock')
df = pd.concat([df1, df2], axis=1, keys=('min','max'))
df.columns = df.columns.map('_'.join)
print (df)
min_Date min_relativevolatility max_Date max_relativevolatility
Stock
AA.csv 2012-11-23 0.010791 2012-11-28 0.030102
ZION.csv 2012-02-14 0.016287 2012-02-15 0.018929
和weekday_name
汇总mean
:
df = (df.groupby(['Stock', df['Date'].dt.weekday_name])['relativevolatility']
.mean()
.reset_index(name='means'))
print (df)
Stock Date means
0 AA.csv Friday 0.016923
1 AA.csv Monday 0.016428
2 AA.csv Thursday 0.017448
3 AA.csv Tuesday 0.018386
4 AA.csv Wednesday 0.020324
5 ZION.csv Tuesday 0.016287
6 ZION.csv Wednesday 0.018929