我已将汽车的 x,y 坐标添加到 Pandas 中。我希望能够计算某个区域有多少辆车。在本例中,我想获取 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 中的循环:在(Pandas)引擎盖下,实现了循环)。
您可以使用以下内容:
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)
这里的逻辑在于比较,通过 bool 逻辑组合起来。您需要注意括号,否则事情会变得困惑: y >= 1
或编辑为y <= 3
,然后将结果和编辑为 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。
关于Python Panda 根据多列计算出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66283166/