Python Forum
change array column values without loop
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
Reply
#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
Reply
#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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Get an average of the unique values of a column with group by condition and assign it klllmmm 0 222 Feb-17-2024, 05:53 PM
Last Post: klllmmm
  Converting column of values into muliple columns of counts highland44 0 205 Feb-01-2024, 12:48 AM
Last Post: highland44
  Loop over an an array of array Chendipeter 1 529 Nov-28-2023, 06:37 PM
Last Post: deanhystad
  Loop through values and compare edroche3rd 6 628 Oct-18-2023, 04:04 PM
Last Post: edroche3rd
  output values change akbarza 3 487 Oct-18-2023, 12:30 PM
Last Post: deanhystad
  Loop through json file and reset values [SOLVED] AlphaInc 2 1,962 Apr-06-2023, 11:15 AM
Last Post: AlphaInc
  Change a numpy array to a dataframe Led_Zeppelin 3 1,065 Jan-26-2023, 09:01 PM
Last Post: deanhystad
  PowerBI: Using Python Regex to look for values in column MarcusR44 1 920 Oct-14-2022, 01:03 PM
Last Post: ibreeden
  How to combine multiple column values into 1? cubangt 15 2,631 Aug-11-2022, 08:25 PM
Last Post: cubangt
  Creating a loop with dynamic variables instead of hardcoded values FugaziRocks 3 1,430 Jul-27-2022, 08:50 PM
Last Post: rob101

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020