繁体   English   中英

确定网格中连续相同点的数量

[英]Determine number of consecutive identical points in a grid

我有 dataframe 和网格大小是 12*8
我想计算连续红点的数量(仅在垂直方向)并用它创建新列(col = Continuous red),对于蓝色它将为零

例如

X y red/blue consecutive red 
1 1  blue    0
1 3  red     3     
1 4  red     3
1 2  blue    0
1 5  red     3
9 4  red     5

[![在此处输入图像描述][1]][1] 在此处输入图像描述 已经有前 3 列的数据

from sklearn.neighbors import BallTree 

red_points = df[df.red/blue== red]
blue_points = df[df.red/blue!= red]

tree = BallTree(red_points[['x','y']], leaf_size=40, metric='minkowski')

distance, index = tree.query(df[['x','y']], k=2)

我不知道这样的算法(很可能有一个),但编写算法并不难(我使用 numpy 因为我已经习惯了,因为您可以轻松地使用 CUDA 加速并移植到其他数据科学 python 工具)。

数据(0=蓝色,1=红色):

import numpy as np
import pandas as pd
# Generating dummy data for testing
ROWS=10
COLS=20
X = np.random.randint(2, size=(ROWS, COLS))
# Visualizing
df = pd.DataFrame(data=X)
bg='background-color: '
df.style.apply(lambda x: [bg+'red' if v>=1 else bg+'blue' for v in x])

在此处输入图像描述

算法:

result = np.zeros((ROWS,COLS),dtype=np.int)
for y,x in np.ndindex(X.shape):
    if X[y, x]==0:
        continue
    cons = 1 # consecutive in any direction including current
    # Going backwward while we can
    prev = y-1
    while prev>=0:
        if X[prev,x]==0:
            break
        cons+=1
        prev-=1
    # Going forward while we can
    nxt = y+1
    while nxt<=ROWS-1:
        if X[nxt,x]==0:
            break
        cons+=1
        nxt+=1
    result[y,x]=cons
df2 = pd.DataFrame(data=result)
df2.style.apply(lambda x: [bg+'red' if v>=1 else bg+'blue' for v in x])

结果:

在此处输入图像描述

请注意,在 numpy中,第一个坐标表示行索引(在您的情况下为 y),第二个坐标表示列(在您的情况下为 x),如果要交换到 x,y,可以对数据使用转置

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM