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

如何用排除7的列均值整数值替换DataFrame中的数值7?

解决方法

可以通过两步操作实现需求:先计算每列排除7后的均值并四舍五入,再将原DataFrame中的7替换为对应列的计算值。

完整代码实现

import pandas as pd

# 初始化示例数据
df = pd.DataFrame({
    'a': [1, 2, 3],
    'b': [3, 0, -1],
    'c': [4, 7, 6],
    'd': [7, 7, 6]
})

# 计算每列排除7后的均值并四舍五入,处理全7列的边界情况
replace_values = df.apply(lambda col: round(col[col != 7].mean()) if (col != 7).any() else 7)

# 将原DataFrame中的7替换为对应列的计算值
result_df = df.where(df != 7, replace_values, axis=1)

print(result_df)

代码解释

  1. 计算替换值:

    • 使用df.apply()遍历每一列,对每列筛选出不等于7的元素col[col !=7]
    • 计算筛选后元素的均值mean(),再用round()四舍五入为整数
    • 加入判断条件if (col !=7).any(),避免列中全是7时出现均值计算错误,这种情况直接保留7
  2. 替换操作:

    • 使用df.where()方法:当原DataFrame中的值不等于7时保留原值,否则用replace_values中对应列的数值替换
    • 指定axis=1确保按列匹配替换值,避免跨行错误

输出结果

a  b  c  d
0  1  3  4  2
1  2  0  3  2
2  3 -1  6  6

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 04:55:24