Python Forum
replace sets of values in an array without using loops
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
replace sets of values in an array without using loops
#4
You can write the code as follows to display values if TypeError encountered:
import numpy as np
import sys

A = np.array([1, 2, 3])
M = np.zeros((10, 10), dtype=float)
N = np.copy(M)
P = np.copy(M)

# Explicitly on 1 location
r = 3
c = 2
M[r, c : c + 3] = A
print(f"\nM(r, c:c_3): {M[r, c:c+3]}")

# now on 2 locations
# with a loop
r = np.array([3, 5])
c = np.array([2, 5])

for i in range(2):
    try:
        N[r[i], c[i] : c[i] + 3] = A
    except TypeError:
        print(f"First loop: Values when TypeError occurs:,  i: {i}, c[i]: {c[i]}")
        sys.exit(-1)

# without a loop
i = np.arange(2)
j = c[i] + 3 * np.ones(2, dtype=int)
k = np.ones((2, 1), dtype=int) * A

try:
    P[r[i], c[i] : j[i]] = k[i]
except TypeError:
    print(
        f"\nTypeError, Values when attempting P[r[i], c[i]:j[i]]=k[i]:\n"
        f"    i: {i}, r[i]: {r[i]}, c[i]: {c[i]}, j[i]: {j[i]}"
    )
    sys.exit(-1)
output shows where error occurs:
Output:
M(r, c:c_3): [1. 2. 3.] TypeError, Values when attempting P[r[i], c[i]:j[i]]=k[i]: i: [0 1], r[i]: [3 5], c[i]: [2 5], j[i]: [5 8]
Reply


Messages In This Thread
RE: replace sets of values in an array without using loops - by Larz60+ - Jun-20-2022, 08:29 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Data sets comparison Fraetos 0 1,432 Sep-14-2021, 06:45 AM
Last Post: Fraetos
  Keep inner Values of 2D array timste 0 1,590 Jul-26-2021, 09:04 AM
Last Post: timste
  Mann Whitney U-test on several data sets rybina 2 2,127 Jan-05-2021, 03:08 PM
Last Post: rybina
  Least-squares fit multiple data sets multiverse22 1 2,300 Jun-06-2020, 01:38 AM
Last Post: Larz60+
  replace nan values by mean group by date.year, date.month wissam1974 5 8,544 Feb-19-2020, 06:25 PM
Last Post: AnkitGupta
  Identifying consecutive masked values in a 3D data array chai0404 12 5,844 Feb-01-2020, 12:59 PM
Last Post: perfringo
  Clustering for imbalanced data sets dervast 0 1,641 Sep-25-2019, 06:34 AM
Last Post: dervast
  Trying to replace for loops with numpy vspoloni 8 9,552 Aug-04-2019, 07:09 AM
Last Post: paul18fr
  Match two data sets based on item values klllmmm 7 6,532 Mar-29-2017, 02:33 PM
Last Post: zivoni

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020