[英]How to count the values of a pandas groupby that meet a certain condition
[英]How to count values that meet a condition in a loop dataframe?
我有一個熊貓df
與一系列Distanz
,並在一系列Zielcode
。 我需要將 Distanz 除以重復的間隔數。 所以第一個不為零的間隔將被除以one
,第二個間隔除以three
,第三個間隔除以two
。
Distanz Zielcode
0.0 0
0.0 0
1.1 2
0.0 0
8.0 7
8.0 7
8.0 7
0.0 0
3.4 1
3.4 1
0.0 0
如何計算整個系列中滿足這種重復條件的區間數,並將值 distanz 除以該計數?
所需的輸出應如下所示:
Distanz Zielcode Distanz - Output
0.0 0 0.0
0.0 0 0.0
1.1 2 1.1
0.0 0 0.0
8.0 7 2.7
8.0 7 2.7
8.0 7 2.7
0.0 0 0.0
3.4 1 1.7
3.4 1 1.7
0.0 0 0.0
我會分不同的步驟來解決這個問題。
識別重復元素:
block = ((df['Distanz'].shift() != df['Distanz']) | (df['Zielcode'].shift() != df['Zielcode'])).cumsum()
這給出:
0 1 1 1 2 2 3 3 4 4 5 4 6 4 7 5 8 6 9 6 10 7 dtype: int32
計算每個塊的大小:
count = df.groupby(block).apply(lambda x: x.assign(count=len(x)) )['count'].reset_index(level=0, drop=True)
這給出:
0 2 1 2 2 1 3 1 4 3 5 3 6 3 7 1 8 2 9 2 10 1 Name: count, dtype: int64
計算新列:
df['Distanz - Output'] = df['Distanz'] / count
數據框變為:
Distanz Zielcode Distanz - Output
0 0.0 0 0.000000
1 0.0 0 0.000000
2 1.1 2 1.100000
3 0.0 0 0.000000
4 8.0 7 2.666667
5 8.0 7 2.666667
6 8.0 7 2.666667
7 0.0 0 0.000000
8 3.4 1 1.700000
9 3.4 1 1.700000
10 0.0 0 0.000000
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.