[英]comparing values of 2 columns from same pandas dataframe & returning value of 3rd column based on comparison
[英]Weighted average, grouped by day, of 2 columns based on criteria in 3rd column of pandas dataframe
我有一個熊貓數據框
import pandas as pd
df = pd.DataFrame({'Col1' : 16 * ['A', 'B', 'C'],
'Col2' : np.random.rand(48),
'Col3' : np.random.randint(5, 20, 48)},
index = pd.date_range('2017-01-01', periods=48, freq='H'))
In [1]: df.tail()
Out [1]:
Col1 Col2 Col3
2017-01-02 19:00:00 B 0.144572 7
2017-01-02 20:00:00 C 0.740500 11
2017-01-02 21:00:00 A 0.357077 19
2017-01-02 22:00:00 B 0.652536 9
2017-01-02 23:00:00 C 0.022437 8
我想返回一個數據框,按日期顯示 Col3 的加權平均值,其中 Col2 是權重,Col1 是“B”或“C”,而忽略“A”。 這將返回如下所示的內容。
WtdAvg
2017-01-01 XX.X
2017-01-02 YY.Y
過濾數據幀,以除去其中的值是Col1中“A”,然后執行groupby
使用np.average
:
df[df['Col1'] != 'A'].groupby(pd.TimeGrouper('D')) \
.apply(lambda grp: np.average(grp['Col3'], weights=grp['Col2']))
結果輸出(使用np.random.seed([3,1415])
作為隨機狀態種子):
2017-01-01 11.975517
2017-01-02 12.411798
np.random.seed([3,1415])
df = pd.DataFrame({'Col1' : 16 * ['A', 'B', 'C'],
'Col2' : np.random.rand(48),
'Col3' : np.random.randint(5, 20, 48)},
index = pd.date_range('2017-01-01', periods=48, freq='H'))
d1 = df.query('Col1 != "A"').drop('Col1', 1)
d2 = d1.assign(Prod=d1.prod(1)).groupby(pd.TimeGrouper('D'))['Col2', 'Prod'].sum()
d2.Prod.div(d2.Col2)
2017-01-01 11.975517
2017-01-02 12.411798
Freq: D, dtype: float64
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.