[英]How to change values of a dataframe through groupby in pandas
這里有一個數據框:
print te_c.head(10)
Price Vol tradeDate
0 9 1 1994-05-09
1 3 2 1994-05-10
2 3 2 1994-05-10
3 3 2 1994-05-10
4 3 2 1994-05-10
5 4 3 1994-05-11
6 4 3 1994-05-11
7 4 3 1994-05-11
8 4 3 1994-05-11
9 5 4 1994-05-12
和清單:
te_index = range(1,te_c.drop_duplicates('tradeDate').shape[0] + 1)
現在我想按'tradeDate'
將te_c
'tradeDate'
,並為每個組讓每個'Vol' * te_index[i]
( i
from range(len(te_index))
),然后使用此新數據重置'Vol'
並所需的輸出是這樣的:
Price Vol tradeDate
0 9 1 1994-05-09
1 3 4 1994-05-10
2 3 4 1994-05-10
3 3 4 1994-05-10
4 3 4 1994-05-10
5 4 9 1994-05-11
6 4 9 1994-05-11
7 4 9 1994-05-11
8 4 9 1994-05-11
9 5 16 1994-05-12
所以我嘗試在groupby函數中使用for循環:
for name, group in te_c.groupby('tradeDate'):
i = 0
for j in range(group.shape[0]):
group.ix[j, 'Vol'] = group.ix[j, 'Vol'] * te_index[i]
i += 1
但是我的代碼不起作用,並具有:
關鍵錯誤:0L
我也嘗試使用.apply()
但是不知道如何將組乘以每個te_index
。 我應該如何編碼以解決此問題?
編輯:此計算只是我希望通過數據幀進行的計算之一,我也想計算類似group.ix[j, 'Vol'] = group.ix[j, 'Vol'] * te_index[-(i+1)] / sum(te_index)
或group.ix[j, 'Price'] = group.ix[j, 'Price'] * (te_index[i] * weights[i])
您可以使用該信息group index
存儲在grouper
一個屬性groupby
對象:
te_c['new_vol'] = te_c.Vol.mul(te_c.groupby('tradeDate').grouper.group_info[0] + 1)
Price Vol tradeDate new_vol
0 9 1 1994-05-09 1
1 3 2 1994-05-10 4
2 3 2 1994-05-10 4
3 3 2 1994-05-10 4
4 3 2 1994-05-10 4
5 4 3 1994-05-11 9
6 4 3 1994-05-11 9
7 4 3 1994-05-11 9
8 4 3 1994-05-11 9
9 5 4 1994-05-12 16
您還可以將group_info[0]
添加為新column
以方便進行其他計算,如下所示:
df['group_info'] = df.groupby('tradeDate').grouper.group_info[0] + 1
Price Vol tradeDate group_info
0 9 1 1994-05-09 1
1 3 2 1994-05-10 2
2 3 2 1994-05-10 2
3 3 2 1994-05-10 2
4 3 2 1994-05-10 2
5 4 3 1994-05-11 3
6 4 3 1994-05-11 3
7 4 3 1994-05-11 3
8 4 3 1994-05-11 3
9 5 4 1994-05-12 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.