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

如何在DataFrame中对指定列执行除法运算?(含除以100、90场景)

Pandas DataFrame列除法操作解决方案

Hey there! Let's break down how to handle both of your DataFrame column division needs clearly:


1. 将DataFrame中选中的列除以100

Depending on whether you're targeting a single column or multiple columns, here are the most efficient approaches:

  • Single column: If you want to divide just one column (say target_col) by 100, you can directly assign the result back to the column:

    # 修改原DataFrame
    df['target_col'] = df['target_col'] / 100
    
    # 或者创建副本,不修改原数据
    df_copy = df.copy()
    df_copy['target_col'] = df_copy['target_col'] / 100
    
  • Multiple columns: For several columns (e.g., col_a, col_b, col_c), use a list to select them and perform the division in one go:

    selected_cols = ['col_a', 'col_b', 'col_c']
    # 修改原DataFrame
    df[selected_cols] = df[selected_cols] / 100
    
    # 创建副本的版本
    df_copy = df.copy()
    df_copy[selected_cols] = df_copy[selected_cols] / 100
    

注意:如果你的列包含非数值类型(比如字符串),先转换为数值类型再操作,否则会报错:

df[selected_cols] = df[selected_cols].astype(float)

2. 将df1中的col2、col3列除以90

This is a specific case of the multi-column scenario above. Here's the direct code you can use:

方式1:直接修改原DataFrame df1

# 直接对指定列执行除法并赋值
df1[['col2', 'col3']] = df1[['col2', 'col3']] / 90

方式2:保留原DataFrame,生成修改后的副本

If you don't want to alter the original df1, create a copy first:

df1_modified = df1.copy()
df1_modified[['col2', 'col3']] = df1_modified[['col2', 'col3']] / 90

同样,如果col2或col3不是数值类型,先转换:

df1[['col2', 'col3']] = df1[['col2', 'col3']].astype(float)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 15:22:50