仅将更改应用于未知边界(墙)内的表

时间:2018-09-24 21:26:09

标签: python python-3.x python-2.7 pandas matplotlib

我希望循环仅将“墙”内的表格单元从0更改为5。 “墙”是用户定义的,根据坐标可以是任何形状。 该图仅用于可视化。

import matplotlib.pyplot as plt 
import pandas as pd

wallPointsX = [5,5,30,30,55,55,5]
wallPointsY = [5,30,30,55,55,5,5]

df = pd.DataFrame(0, index=range(60), columns=range(60))

for x in range(0, 60):
    for y in range(0, 60):
        df[x][y] = 5 #Should only apply inside "walls"

plt.plot(wallPointsX, wallPointsY)
plt.pcolor(df)
plt.show()

Result plot

1 个答案:

答案 0 :(得分:0)

好,花了我一些时间,但是这样做很有趣。这里的想法是首先在定义墙的坐标之外创建连续的path。接下来,创建一个对象Path。现在,您遍历DataFrame中的每个点,然后使用Path查看所创建的contains_point是否包含该(x,y)点。我还必须在x==55 and (5<y<=55)语句中使用条件if,以便包括与 最右边的墙。

import matplotlib.path as mplPath
import numpy as np

wallPointsX = [5,5,30,30,55,55,5]
wallPointsY = [5,30,30,55,55,5,5]

# Create a continuous path across the wall coordinates
path = np.array([list(i) for i in zip(wallPointsX, wallPointsY)])
Path = mplPath.Path(path)

df = pd.DataFrame(0, index=range(60), columns=range(60))

for x in range(0, 60):
    for y in range(0, 60):
        if Path.contains_point((x,y)) or (x==55 and (5<y<=55)):
            df[x-1][y-1] = 5 #Should only apply inside "walls"

plt.plot(wallPointsX, wallPointsY)
plt.pcolor(df)

输出

enter image description here