Issue
Sorry for the title but basically I'm dealing with a dataset that looks like a pacman game.
So I need to find the coordinates of the closest ghosts to the pacman.
import pandas as pd
pacman = [
list(" G"),
list(" P G "),
list(" G "),
list(" G "),
list(" G "),
]
df = pd.DataFrame(pacman)
print(df)
0 1 2 3 4 5 6 7 8 9 10
0 G
1 P G
2 G
3 G
4 G
I expect (0, 10) and (1, 5) as an output since they are the coordinates of the closest ghosts to pacman
My code below gives only (0, 10)
. Can you explain why please or give other solution ?
data = df.values.flatten()
g_indices = np.where(data == 'G')[0]
p_indices = np.where(data == 'P')[0]
min_index = np.argmin(np.abs(g_indices - p_indices))
g_index = g_indices[min_index]
coordinates = (df.iloc[:, g_index].idxmax(), g_index)
print(coordinates)
(0, 10)
Solution
2D
Assuming you want the closest(s) in terms of euclidean distance:
x, y = np.where(df.eq('P')) # get pacman position
xg, yg = np.where(df.eq('G')) # get ghosts positions
dist = (xg-x)**2 + (yg-y)**2 # compute square of distance
mask = dist == dist.min() # get minimum distance
# format output
closest = list(zip(df.index[xg[mask]], df.columns[yg[mask]]))
Output:
[(2, 4)]
Other example:
# input
0 1 2 3 4 5 6 7 8 9 10
0 G G
1 G P G G
2 G G
3 G
4 G
# output
[(1, 1), (1, 3), (2, 2)]
1D
If you really want to consider your input as 1D, do the same in 1D and restore the original indices with numpy.unravel_index
:
a = df.to_numpy().ravel()
x = np.where(a == 'P')[0]
xg = np.where(a == 'G')[0]
dist = abs(xg-x)
closest = list(zip(*np.unravel_index(xg[dist==dist.min()], df.shape)))
closest
# [(0, 10), (1, 5)]
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.