[英]Python Panda count occurences depending on multiple columns
我已将我的汽车的 x,y 坐标添加到熊猫中。 我希望能够计算某个区域有多少辆车。 在这种情况下,我想获得 x = 2 和 y=1 到 3 中所有汽车的计数。我想获得计数 2,因为位置 (2,2) 中没有汽车。 我还不太习惯 pandas 所以我想循环所有东西。
def index_used_x_y(x,y):
try:
cars .loc[(cars ['x'] == x) & (cars ['y'] == y)].index
return True
except ValueError:
return False
cars = pd.DataFrame()
cars ['x'] = np.array([1,1,1,2,2,3,3,3,4,4,4])
cars ['y'] = np.array([1,2,3,1,3,1,2,3,1,2,3])
count_cars = 0
print(cars )
x_from = 2
x_to = 2
y_from = 1
y_to = 3
for x in range(x_from,x_to+1):
for y in range(y_from,y_to+1):
if index_used_x_y(x,y):
count_cars +=1
print(count_cars )
我知道您提到您想使用循环,但是 Pandas 的强大功能是避免循环(至少在普通 Python 中的循环:在(熊猫)引擎盖下,实现了循环)。
您可以使用以下内容:
import pandas as pd
cars = pd.DataFrame({'x': [1,1,1,2,2,3,3,3,4,4,4],
'y': [1,2,3,1,3,1,2,3,1,2,3]})
count = ( (cars['x'] == 2) & ((cars['y'] >= 1) | (cars['y'] <= 3)) ).sum()
print(count)
这里的逻辑在比较中,通过 boolean 逻辑组合。 您需要注意括号,否则事情会搞砸: y >= 1
或ed 与y <= 3
,结果是 then和ed 与x == 2
。
中间系列,在求和之前,如下:
0 False
1 False
2 False
3 True
4 True
5 False
6 False
7 False
8 False
9 False
10 False
dtype: bool
并且.sum()
方法会将True
解释为 1,将False
解释为 0,结果总共为 2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.