[英]Calculating the differences between unique values in the column and averaging by number of unique values with grouping by another column in Python
我有一個 dataframe,需要做一些自定義計算。
Protocol Visit Day
111 1 1
111 1 1
111 1 1
111 2 15
111 2 15
111 2 15
111 3 29
111 3 29
222 2 14
222 2 14
222 2 14
222 3 28
222 3 28
222 3 28
可重現的輸入:
{'Protocol ': {0: 111, 1: 111, 2: 111, 3: 111, 4: 111, 5: 111, 6: 111, 7: 111, 8: 222, 9: 222, 10: 222, 11: 222, 12: 222, 13: 222, 14: 222}, 'Visit': {0: 1, 1: 1, 2: 1, 3: 2, 4: 2, 5: 2, 6: 3, 7: 3, 8: 1, 9: 2, 10: 2, 11: 2, 12: 3, 13: 3, 14: 3}, 'Day': {0: 1, 1: 1, 2: 1, 3: 15, 4: 15, 5: 15, 6: 29, 7: 29, 8: 1, 9: 14, 10: 14, 11: 14, 12: 28, 13: 28, 14: 28}}
我想要什么:
Day
列中的值之間的唯一值之間的差異。 例如,對於協議 111,它將是15-1 = 14
和29 - 15 = 14
。 相同的邏輯應該適用於特定協議列中的所有數字,因為我將為每個協議提供更多。
14 + 14 = 28/3 = 9.3
。 3 表示用於計算差異的 3 個唯一值 - 1, 15, 29
。 對於協議 222,它將是28-14 = 14
除以 2(唯一值的數量)。 結果7
。
預計 output
Protocol Average difference
111 9.3
222 7
首先對兩列使用DataFrame.drop_duplicates
,然后聚合 lambda function 以獲得差異平均值:
#remove traling whitespaces in columns names
df.columns = df.columns.str.strip()
df1 = (df.drop_duplicates(['Protocol','Day'])
.groupby('Protocol')['Day']
.agg(lambda x: x.diff().sum() / len(x))
.reset_index(name='Average difference'))
print (df1)
Protocol Average difference
0 111 9.333333
1 222 7.000000
或者:
df1 = (df.drop_duplicates(['Protocol','Day'])
.groupby('Protocol')['Day']
.agg(lambda x: x.diff().fillna(0).mean())
.reset_index(name='Average difference'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.