如何使用 pandas 和 python 从列中减去单个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33140496/
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-08-19 12:51:11  来源:igfitidea点击:

How can i substract a single value from a column using pandas and python

pythonpandas

提问by jax

i have one data frame suppose:

我有一个数据框假设:

name age hb
ali  34  14
jex  16  13
aja  24  16
joy  23  12

i have a value say "5" that i want to substract from each member of column "hb"

我有一个值说“5”,我想从“hb”列的每个成员中减去

new column could be:

新列可能是:

hb
9
8
11
7

What is the best method to do this...

什么是最好的方法来做到这一点...

thanks and regards.

感谢致敬。

采纳答案by Anand S Kumar

Simply subtract the scalar value from the pandas.Series, for numerical columns pandas would automatically broadcast the scalar value and subtract it from each element in the column. Example -

只需从 中减去标量值pandas.Series,对于数字列,pandas 会自动广播标量值并从列中的每个元素中减去它。例子 -

df['hb'] - 5 #Where `df` is your dataframe.

Demo -

演示 -

In [43]: df
Out[43]:
  name  age  hb
0  ali   34  14
1  jex   16  13
2  aja   24  16
3  joy   23  12

In [44]: df['hb'] - 5
Out[44]:
0     9
1     8
2    11
3     7
Name: hb, dtype: int64

回答by Hackaholic

try this:

尝试这个:

df["hb"] - 5

df["hb"]will select hbcolumn and subtract 5 from it

df["hb"]将选择hb列并从中减去 5

回答by Colin Anthony

You can also do this using the pandas.apply function

您也可以使用 pandas.apply 函数执行此操作

df["hb"] = df["hb"].apply(lambda x: x - 5)

df["hb"] = df["hb"].apply(lambda x: x - 5)

回答by Durmus

If you are using this:

如果你正在使用这个:

df['hb'] - 5

you will get a new single column. But if you want to keep the rest then you have to use:

你会得到一个新的单列。但是,如果您想保留其余部分,则必须使用:

df['hb'] -= 5