将 Pandas DataFrame 中的每个数值设为负数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25315549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:22:26  来源:igfitidea点击:

Make every numeric value in a pandas DataFrame negative

pythonpandasdataframe

提问by clintval

How can I make every pandasDataFrame value negative? I couldn't find this answer listed and thought it may provide a good reference for anyone learning how to work with data in the pandasDataFrame.

如何使每个pandasDataFrame 值为负?我找不到列出的这个答案,并认为它可以为任何学习如何处理pandasDataFrame 中的数据的人提供很好的参考。

In [1]: frame
Out[1]:
       position
index
0          6
1          7
2          7
3          7
4          8
5          9
6          1
7          1

回答by joris

Just do - frame(or *-1):

只是做- frame(或*-1):

In [122]: -frame
Out[122]:
       position
index
0            -6
1            -7
2            -7
3            -7
4            -8
5            -9
6            -1
7            -1

As noted by others, this will not work if you also have non-numeric columns. A way to select all numeric columns:

正如其他人所指出的,如果您还有非数字列,这将不起作用。一种选择所有数字列的方法:

frame.select_dtypes(include=[np.number])

And if already negative values should stay negative, indeed use abs()as noted by @Easypeasy. Then this becomes:

如果已经负值应该保持负值,确实abs()按照@Easypeasy 的说明使用。然后就变成了:

- frame.select_dtypes(include=[np.number]).abs()

回答by clintval

Use pandas.DataFrame.apply()like so:

像这样使用pandas.DataFrame.apply()

In [1]: f = lambda x: -x; frame.apply(f, axis=1)
Out[1]:
       position
index
0         -6
1         -7
2         -7
3         -7
4         -8
5         -9
6         -1
7         -1

回答by abarnert

You can apply any operator or across a column. To mutate it in-place, just multiply the column by -1:

您可以应用任何运算符或跨列应用。要就地改变它,只需将列乘以 -1:

>>> frame = pd.DataFrame({'position': [6,7,7,7,8,9,1,1]})
>>> frame['position'] *= -1
>>> frame
   position
0        -6
1        -7
2        -7
3        -7
4        -8
5        -9
6        -1
7        -1

But in this case, you don't even need to specify a column, because it's the only one you have, so just:

但在这种情况下,您甚至不需要指定一列,因为它是您拥有的唯一一列,所以只需:

>>> frame *= -1

If you want to create a copy instead of mutating in-place, that's even simple:

如果你想创建一个副本而不是就地变异,那就更简单了:

>>> frame * -1

… or, equivalently and even more simply:

……或者,等效地甚至更简单地:

>>> -frame

回答by Easypeasy

The other answers will do what you want. However, if you already have some negative numbers in your DataFrame, but want all to be, then this will do:

其他答案会做你想做的。但是,如果您的 DataFrame 中已经有一些负数,但希望全部为负数,则可以这样做:

frame.apply(lambda x: -x.abs(), axis=1)

frame.apply(lambda x: -x.abs(), axis=1)