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
  How to add a number to each column separtely in numpy array? Oliver 0 75 Jul-02-2020, 02:55 PM
Last Post: Oliver
  Assigning Column nunique values to another DataFrame column Pythonito 1 118 Jun-26-2020, 06:52 AM
Last Post: hussainmujtaba
  How to find and change variable values ​​in memory thiagoD 1 196 Jun-08-2020, 03:45 AM
Last Post: bowlofred
  Get values from a split column Pythonito 3 252 Apr-18-2020, 11:35 PM
Last Post: Larz60+
  Double for loop with dates in array leifeng 1 231 Apr-05-2020, 03:27 PM
Last Post: leifeng
  How to compare two columns and highlight the unique values of column two using pandas shubhamjainj 0 441 Feb-24-2020, 06:19 AM
Last Post: shubhamjainj
  Getting duplicate column values but same row values from a csv smidtol 1 246 Feb-10-2020, 08:43 PM
Last Post: Larz60+
  Do Calculation between Rows based on Column values - Pandas Dataframe ahmedwaqas92 0 349 Jan-28-2020, 07:06 AM
Last Post: ahmedwaqas92
  Need help with For Loop logic for reading docx Table column data vintysaw 2 561 Jan-10-2020, 06:36 AM
Last Post: vintysaw
  Search Excel column values jonzee 1 527 Dec-21-2019, 02:38 AM
Last Post: Clunk_Head

Forum Jump:


Users browsing this thread: 1 Guest(s)