You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从多行Pandas Series中减去单行Pandas Series?

问题

我有一个包含962列的Pandas DataFrame df:

print(df)
         ID  doy  WaitID  Year  ...       212
386    1895  193   14507  2001  ...  0.407672
389    1899  192   14511  2001  ...  0.000000
390    1900  204   14512  2001  ...  0.000000
391    1902  145   14514  2001  ...  2.251606
395    1877  204   14491  2001  ...  1.727977
...     ...  ...     ...   ...  ...       ...
20279   369  189   32767  2001  ...  1.727977
20281   371  174   32767  2001  ...  2.038362
20292   356  170   32767  2001  ...  0.407672
20295   359  174   32767  2001  ...  0.815345
20296   360  201   32767  2001  ...  2.038362

另有一个经切片得到的单行均值Pandas Series mean_df:

print(mean_df)
   ID     WaitID  ...        212        213    Year
0  3.1        3.0  ...  35.939027  24.231911  2000.0

我希望将df中列名“212”的值减去mean_df中同列名的值,尝试了以下代码却得到NaN:

x = df['212'].subtract(mean_df['212'], fill_value = 0)
print(x)

         ID  doy  WaitID  Year  ...       212  212_x
386    1895  193   14507  2001  ...  0.407672    NaN
389    1899  192   14511  2001  ...  0.000000    NaN
390    1900  204   14512  2001  ...  0.000000    NaN
391    1902  145   14514  2001  ...  2.251606    NaN
395    1877  204   14491  2001  ...  1.727977    NaN
...     ...  ...     ...   ...  ...       ...
20279   369  189   32767  2001  ...  1.727977    NaN
20281   371  174   32767  2001  ...  2.038362    NaN
20292   356  170   32767  2001  ...  0.407672    NaN
20295   359  174   32767  2001  ...  0.815345    NaN
20296   360  201   32767  2001  ...  2.038362    NaN

请问如何实现从多行Pandas Series中减去单行Pandas Series?

解决方法

出现NaN的核心原因是索引不匹配:df['212']的索引是原DataFrame的行索引(如386、389),而mean_df['212']的索引是0,Pandas做对齐运算时找不到匹配的索引,因此返回NaN。

以下是几种可行的解决方式:

  • 直接提取标量值:取出mean_df['212']的标量数值,Pandas会自动将其广播到整个Series:

    x = df['212'] - mean_df['212'].iloc[0]
    

    也可以用.values[0]实现同样效果:

    x = df['212'] - mean_df['212'].values[0]
    
  • 忽略索引运算:使用subtract方法时,传入标量值而非带索引的Series,或者重置索引对齐:

    x = df['212'].subtract(mean_df['212'].values[0], fill_value=0)
    

    或者重置mean_df['212']的索引使其与df['212']匹配:

    x = df['212'].subtract(mean_df['212'].reset_index(drop=True), fill_value=0)
    
  • 多列批量处理:如果需要对多列执行相同的均值减法,可以直接对DataFrame操作,Pandas会按列自动广播:

    # 筛选数值列,排除非数值列(如ID、doy等)
    numeric_cols = df.select_dtypes(include=['number']).columns
    df[numeric_cols] = df[numeric_cols] - mean_df[numeric_cols].iloc[0]
    

内容的提问来源于stack exchange,提问作者Thomas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 04:54:57