如何从数字中减去 Pandas DataFrame 的每一行?

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

How to subtract each row of a pandas DataFrame from a number?

pythonpandasdataframesubtraction

提问by dana111

Say I have a DataFrame:

假设我有一个 DataFrame:

ds = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','Average'])
ds
      A         B         C      Average
1  1.099679  0.042043  0.083903  0.410128
2  0.268205  0.718933  1.459374  0.758887
3  0.680566  0.538655  0.038236  1.169403

How do I subtract (and replace with the result) A, B and C in row one with the average in row 1?

如何减去(并用结果替换)第一行中的 A、B 和 C 与第一行中的平均值?

回答by Alex Riley

One relatively simple way is to use the submethod (I'm assuming that Averageis always the last column):

一种相对简单的方法是使用该sub方法(我假设它Average始终是最后一列):

ds[ds.columns[:-1]].sub(ds.Average, axis=0)

This does the following:

这将执行以下操作:

  • ds[ds.columns[:-1]]is a DataFrame containing all but the last column (Average) of ds.

  • .sub(ds.Average, axis=0)subtracts the row-values in the Averagecolumn from the corresponding rows in the DataFrame.

  • ds[ds.columns[:-1]]是一个包含除最后一列 ( Average)之外的所有数据帧ds

  • .sub(ds.Average, axis=0)AverageDataFrame 中的相应行中减去列中的行值。

To alter your original ds, make sure to rebind the relevant columns of dsto the new DataFrame of values:

要更改您的原始ds,请确保将 的相关列重新绑定ds到新的 DataFrame 值:

ds[ds.columns[:-1]] = ds[ds.columns[:-1]].sub(ds.Average, axis=0)

回答by Woody Pride

How about

怎么样

ds['A'] = ds['A'] - ds['Average']
ds['B'] = ds['B'] - ds['Average']
ds['C'] = ds['C'] - ds['Average']

Pandas is easy like that!

Pandas就是这么简单!

Oh, that does it for the entire DF. You only want it for the firs row is that right?

哦,这对整个 DF 都是如此。你只想要第一行是吗?

ds.loc[1, 'A'] = ds.loc[1, 'A'] - ds.loc[1, 'Average']
ds.loc[1, 'B'] = ds.loc[1, 'B'] - ds.loc[1, 'Average']
ds.loc[1, 'C'] = ds.loc[1, 'C'] - ds.loc[1, 'Average']

or in a loop:

或在循环中:

for col in ['A', 'B', 'C']:
    ds.loc[1, col] = df.loc[1, col] - ds.loc[1, 'Average']

and so on...

等等...

if you have thousands of columns then simply do:

如果您有数千列,那么只需执行以下操作:

for col in ds.columns:
    ds[col] = ds[col] - ds['Average']