简体   繁体   中英

Subtracting a number for each element in a column

I have a csv file where I can access one of the columns. For instance I have:

A
2.5
3.5
4.5
5.5

etc.

What I want to do is to subtract all the entries in A by 1.0 for it to become:

B
1.5
2.5
3.5
4.5

Any ideas on how I can do it? I tried numpy.subtract() but it only leads to error.

If you have a numpy array you can subtract a constant from the array like:

>>> A = numpy.array([2.5, 3.5, 4.5, 5.5])
>>> A-1
array([ 1.5,  2.5,  3.5,  4.5])

edit: it's called broadcasting, btw http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html

The easiest way is to use the decrement/increment opperator

A -= 1

This works on the whole array. Loops are just to slow if you can do things with numpy arrays and their great broadcasting capabilities. But pay attention, many of the numpy routines don't work on lists because they are not transforming them to arrays. This might be the reason why numpy.substract() didn't work.

You can "map" a function across the list using the apply named map function:

>>> A = [2.5, 3.5, 4.5, 5.5]
>>> B = map(lambda x: x-1., A)
>>> B
[1.5, 2.5, 3.5, 4.5]
>>>

Where lambda x: x-1 is the anonymous function to which all elements of A are applied. For 2.5 the function returns 2.5-1 , for 3.5 the function returns 3.5-1 and so on.

If you want to do it in-place then you will need a for-loop:

for i in range(len(column)):
   column[i] = column[i] - 1.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM