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

如何用TENURE与MONTHLYCHARGES的乘积替换TOTALCHARGES列的11个NA值

Alright, let's fix those 11 NA values in your TOTALCHARGES column. The goal is to replace each NA with the product of the corresponding TENURE and MONTHLYCHARGES values from the same row, right? Here's how to do this smoothly in both R and Python—two of the most common tools for this kind of dataframe work:

R Solution

If you're using base R, a straightforward ifelse() statement will get the job done quickly:

# Replace NA in TOTALCHARGES with tenure * monthlycharges
df$TOTALCHARGES <- ifelse(is.na(df$TOTALCHARGES), df$TENURE * df$MONTHLYCHARGES, df$TOTALCHARGES)

For a more readable approach (especially if you're working with tidyverse tools), use dplyr's mutate() and case_when():

library(dplyr)

df <- df %>%
  mutate(TOTALCHARGES = case_when(
    is.na(TOTALCHARGES) ~ TENURE * MONTHLYCHARGES,
    TRUE ~ TOTALCHARGES  # Keep existing values where there's no NA
  ))

You can double-check that all NAs are gone with:

sum(is.na(df$TOTALCHARGES))  # Should return 0

Python Solution

In pandas, the fillna() method makes this task super concise:

import pandas as pd

# Replace NA values with the product of the two columns
df['TOTALCHARGES'] = df['TOTALCHARGES'].fillna(df['TENURE'] * df['MONTHLYCHARGES'])

If you prefer more explicit control over which rows you're modifying, use loc to target only the NA rows:

# Directly assign the product to rows where TOTALCHARGES is NA
df.loc[df['TOTALCHARGES'].isna(), 'TOTALCHARGES'] = df['TENURE'] * df['MONTHLYCHARGES']

Verify the fix with:

df['TOTALCHARGES'].isna().sum()  # Should return 0

内容的提问来源于stack exchange,提问作者Seamus O'Leary

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:35:42