Python Forum

Full Version: change array column values without loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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] *= 2
If 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
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.