change array column values without loop - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: change array column values without loop (/thread-18085.html) |
change array column values without loop - khalidreemy - May-05-2019 Hello I need to update a column values of an array without using a loop. Is there any way to update with criteria. 1 0.168425 2 0 3 0 4 0.752781 5 0.235684 I need to double the values below 0.5 , so the result will become like this: 1 0.33685 2 0 3 0 4 0.752781 5 0.471368 RE: change array column values without loop - scidam - May-05-2019 The answer depends on what container did you use to store the data. If you are working with numpy arrays, you can do that as follows: import numpy as np x = np.array([0.16, 0, 0, 0.65, 0.17]) x[x < 0.5] *= 2If your data is presented as a column of Pandas dataframe, you can do it by almost similar way: # df Pandas data frame df[df.iloc[:, <column number>]<0.5] *= 2 RE: change array column values without loop - DeaD_EyE - May-05-2019 List Comprehension with conditional expression: data = [0.16, 0, 0, 0.65, 0.17] result = [x * 2 if x < 0.5 else x for x in data]If you use numpy or pandas, you're using implicit for-loops. But in the numpy case, the for-loop is written in C. Operations on a numpy arrays are much faster than looping and doing the same in Python. To know how you can do broadcast operations with Python, is useful. |