Joanne
Joanne

Reputation: 503

Replacing values in 2D array with NaN value in Python

I have a 2D array (10X10) and I would like to change some values into NaN. The positions of the values I want to change form a rectangle. I know the positions: (row 2 to 6) X (column 1 to 4).

Look like this:

239 247 214 238 234 216 251 307 185 202
257 283 254 337 247 264 247 272 240 300
219 251 268 255 231 259 234 221 244 255
271 231 239 254 206 247 278 228 315 245
212 203 211 243 256 241 262 223 288 228
278 267 216 234 238 187 212 250 255 256
225 244 241 262 292 329 242 236 275 226
267 229 231 241 222 237 218 224 271 199
264 245 245 238 255 225 273 250 251 226
223 231 276 228 243 203 253 236 233 220

239 247 214 238 234 216 251 307 185 202
257 283 254 337 247 264 247 272 240 300
219 nan nan nan nan 259 234 221 244 255
271 nan nan nan nan 247 278 228 315 245
212 nan nan nan nan 241 262 223 288 228
278 nan nan nan nan 187 212 250 255 256
225 nan nan nan nan 329 242 236 275 226
267 229 231 241 222 237 218 224 271 199
264 245 245 238 255 225 273 250 251 226
223 231 276 228 243 203 253 236 233 220

Upvotes: 0

Views: 345

Answers (2)

Sameeresque
Sameeresque

Reputation: 2602

import numpy as np
matr=np.random.rand(10,10)
matr[1:5,0:3]=float('nan') #Python uses zero-based indexing

Upvotes: 1

Chris Loonam
Chris Loonam

Reputation: 5745

Should be as simple as

arr[2:7, 1:5] = np.nan

Upvotes: 1

Related Questions