如何在DataFrame中对指定列执行除法运算?(含除以100、90场景)
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'] / 100Multiple 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

