问题描述
我有数据框,网格大小为 12*8
我想计算连续红点的数量(仅在垂直方向)并用它创建新列(col =连续红色)蓝色它将为零
例如
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',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),您可以使用 transpose如果你想交换到 x,y,你的数据。