Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 change array column values without loop
#1
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
Quote
#2
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
Quote
#3
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.
scidam likes this post
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  change array elements dependent on index SchroedingersLion 1 81 Nov-22-2019, 06:25 AM
Last Post: scidam
  How to change a dataframe column to lower case zhujp98 5 275 Oct-29-2019, 06:42 PM
Last Post: zhujp98
  Loop through folder of Excel Files and extract single column fioranosnake 2 126 Oct-28-2019, 05:19 PM
Last Post: fioranosnake
  Need to copy column of cell values from one workbook to another with openpyxl curranjohn46 3 309 Oct-12-2019, 10:57 PM
Last Post: curranjohn46
  For loop prints strane values? colt 2 197 Sep-22-2019, 02:01 AM
Last Post: ichabod801
  (Python help) Change in logic not breaking 'while' loop? btcg2807 1 121 Sep-18-2019, 09:43 AM
Last Post: Larz60+
  Get all values of for loop with an index BollerwagenIng 2 311 Aug-09-2019, 07:58 AM
Last Post: BollerwagenIng
  Loop through array items dynamically in a certain format bhojendra 3 257 Jun-11-2019, 03:37 AM
Last Post: micseydel
  change to loop amirliker 3 257 Jun-06-2019, 01:08 PM
Last Post: heiner55
  N-Dim array manipulation in a loop, getting IndexError: too many indices for array cesardepaula 1 1,552 Mar-13-2019, 01:39 AM
Last Post: scidam

Forum Jump:


Users browsing this thread: 1 Guest(s)