How to replace only 1d values in 2d array after filter using numpy in python without loop i.e in pythonic way.

I want to filter only t2 rows and replace values in second column ( middle column ).


>>> x = np.array([['t1',10,20],['t2',11,22],['t2',12,23], ['t3',21,32]])

>>> x
array([['t1', '10', '20'],
       ['t2', '11', '22'],
       ['t2', '12', '23'],
       ['t3', '21', '32']], 

replace_value_for_t2_col1 = [100,101]

so expected output is
array([['t1', '10', '20'],
       ['t2', '100', '22'],
       ['t2', '101', '23'],
       ['t3', '21', '32']], 
What i tried was,

Filter rows for t2

>>> x[x[:,0]=='t2']

array([['t2', '11', '22'],
       ['t2', '12', '23']], 

>>> x[x[:,0]=='t2'][:,1] = np.array([101,102])

Seems right, but not replacing. i guess it make a copy when we slice using [:,1], so its not changing in same array.

Please suggest me any brilliant ,simple and pythonic ideas, techniques.

Recommended Answers

gives you a new array

Jump to Post

All 4 Replies

gives you a new array

The pythonic way would be to use a loop.

I would just temporarily convert back to a Python list:

import numpy as np

x = np.array([['t1',10,20],['t2',11,22],['t2',12,23], ['t3',21,32]])
print(x)  # test

# convert temporarily to Python list again
mylist = x.tolist()
mylist2 = ['100', '101']
n = 0
newlist = []
for line in mylist:
    if line[0] == 't2':
        line[1] = mylist2[n]
        n += 1

print(newlist)  # test

# convert back to numpy array
x = np.array(newlist)
print(x)  # show result
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.