如何用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

