简体   繁体   English

如何从 pandas DataFrame 的列中减去单个值

[英]How to substract a single value from column of pandas DataFrame

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.谢谢并恭祝安康。

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.只需从pandas.Series中减去标量值,对于数值列,pandas 会自动广播标量值并从列中的每个元素中减去它。 Example -例子 -

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

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

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

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

If you want this subtraction to be saved in your DataFrame and avoid the old SettingWithCopyWarning , use loc :如果您希望将此减法保存在 DataFrame 中并避免使用旧的SettingWithCopyWarning ,请使用loc

df.loc["hb"] -= 5

Importantly, if you need to use multiple conditions for selecting a value range, put both into the loc call (chaining does not work for this):重要的是,如果您需要使用多个条件来选择值范围,请将两者都放入loc调用中(链接不适用于此):

df.loc[df.age==34,"hb"] -= 5

try this:尝试这个:

df["hb"] - 5

df["hb"] will select hb column and subtract 5 from it df["hb"]将选择hb列并从中减去 5

eval lets you assign the new values directly to your existing column hb : eval允许您将新值直接分配给现有列hb

In [6]: df.eval("hb = hb - 5", inplace=True)

In [7]: df
Out[7]: 
  name  age  hb
0  ali   34   9
1  jex   16   8
2  aja   24  11
3  joy   23   7

Since inplace=True you don't need to assign it back to df .由于inplace=True您不需要将其分配回df

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

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