我有一組這樣的坐標:
np.random.rand(5, 2) * 100
array([[70.89188827, 10.19794602],
[97.59071239, 30.97320455],
[66.47328843, 97.29316592],
[20.86154854, 96.20304524],
[96.56701376, 69.69812926]])
我想將它們轉換為 0-1 矩陣,該矩陣表示 100x100 大小的圖塊,其中 1 表示點(陣列行)位于特定圖塊內。我怎樣才能快速做到這一點?
uj5u.com熱心網友回復:
我對這個問題感到困惑——除了點所在的位置(即網格中的值是 0 或 1)之外,您是否想要一個到處都是 0 的網格,或者您想要一個給定坐標為的漸變圖峰?
假設您想要一個所有值都為 0 或 1 的陣列,看起來您正在嘗試使用 2 列陣列作為索引;對于[70.89188827 10.19794602]隨機陣列中的行,您希望第 70 行和第 10 列(包括零索引)中的圖塊具有值 1,對嗎?
你可以這樣做:
square_size = 100 # how long the side of your array should be.
num_indices = 5 # How many indices to generate.
random_arr = np.random.rand(num_indices, 2) * square_size
# The random array must be made into integers to be used as indices.
random_arr = np.floor(random_arr).astype(int)
# Make the square array to use for tiles.
tile_array = np.zeros((square_size, square_size), dtype=int)
# For each value in random_arr, find that tile in tiles_array and make that tile = 1.
tile_array[random_arr[:, 0], random_arr[:, 1]] = 1
在這種情況下,[70.89188827 10.19794602]您生成的隨機陣列中的行將在[70 10]鋪地板步驟之后變為第 70 行(如果您從 1 數數,則為第 71 行)和第 10 列(如果您從 1 數數,則為第 11 行)將變為 1。
PS如果要tile_array翻轉第70列第10行的tile變成1,可以tile_array = tile_array.T在最后添加。
PPS 在回答評論中發布的第二個問題時——您可以在random_arr = np.floor(random_arr).astype(int)我發布的原始代碼的行之后插入以下代碼。如果有任何重復的行,這些行將被調整以參考下一列中的圖塊。例如,如果 中有兩行[10,13],則和random_arr對應的圖塊將為 1。如果重復的圖塊位于行尾,則將下一行中的第 0 個圖塊標記為 1。[10,13][10,14]
請注意,此方法非常簡單;如果調整后的圖塊與 random_arr 中已經存在的圖塊相同,則它不會做一些聰明的事情并在之后標記該圖塊。例如說random_arr有索引[10,13], [10,13], [10,14]。復制的[10,13]將被調整為[10,14],但在這種情況下,這不會改變哪些瓷磚已經被標記,因為[10,14]已經在random_arr.
幾乎肯定還有比我所做的更好的選擇重復行的方法;我只是不知道。
# unique_rows_packed returns the actual rows in random_arr that are unique,
# as well as the indices of these rows. These are unpacked into
# unique_rows and unique_rows_indices.
unique_rows_packed = np.unique(random_arr, True, axis=0)
unique_rows = unique_rows_packed[0]
unique_rows_indices = unique_rows_packed[1]
# Start with all row indices in random_arr and delete the rows which are unique rows.
# duplicate_rows then only includes the indices of duplicate rows.
indices_arr = np.arange(0, num_indices, 1)
duplicate_rows = np.delete(indices_arr, unique_rows_indices, axis=0)
# Get the values of the duplicate rows.
duplicate_row_vals = random_arr[duplicate_rows]
# Nudge duplicate row values.
for row in range(duplicate_row_vals.shape[0]):
# check if duplicate row is for a tile at the end of a row (i.e. column number = square_size - 1).
# If not, then add 1 to column number.
orig_x, orig_y = duplicate_row_vals[row, 0], duplicate_row_vals[row, 1]
if orig_y < square_size - 1:
duplicate_row_vals[row, 1] = 1
# If tile is at end of row, then adjust the duplicated tile to equal
# the 0th tile in the next row.
else:
duplicate_row_vals[row] = [orig_x 1, 0]
# Concatenate the unique rows values and adjusted duplicate row values to get the final indices.
random_arr = np.concatenate((unique_rows, duplicate_row_vals), axis=0)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/439818.html
