![](/img/trans.png)
[英]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.