简体   繁体   English

为列中的每个元素减去一个数字

[英]Subtracting a number for each element in a column

I have a csv file where I can access one of the columns. 我有一个csv文件,可以在其中访问列之一。 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: 我想要做的是将A中的所有条目都减去1.0,以使其变为:

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. 我尝试了numpy.subtract(),但这只会导致错误。

If you have a numpy array you can subtract a constant from the array like: 如果您有一个numpy数组,则可以从数组中减去一个常量,例如:

>>> 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 编辑:这就是广播,顺便说一句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. 如果您可以使用numpy数组及其强大的广播功能执行操作,则循环只会减慢速度。 But pay attention, many of the numpy routines don't work on lists because they are not transforming them to arrays. 但是请注意,许多numpy例程不适用于列表,因为它们没有将其转换为数组。 This might be the reason why numpy.substract() didn't work. 这可能是numpy.substract()无法正常工作的原因。

You can "map" a function across the list using the apply named map function: 您可以使用apply named map函数在列表中“映射”一个函数:

>>> 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. 其中lambda x: x-1是将A所有元素都应用到的匿名函数。 For 2.5 the function returns 2.5-1 , for 3.5 the function returns 3.5-1 and so on. 对于2.5该函数返回2.5-1 ;对于3.5该函数返回3.5-1 ,依此类推。

If you want to do it in-place then you will need a for-loop: 如果要就地执行此操作,则需要一个for循环:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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