Home > Mobile >  How to calculate an average across multiple columns only if none of the value is missing in Python P
How to calculate an average across multiple columns only if none of the value is missing in Python P

Time:10-29

This is my data:

enter image description here

How can I get the average value of all the columns with string _var and if none of these column has missing value NaN?

CodePudding user response:

You can just use mean() with skipna=False.

# extract the columns based on prefix 
cols = [col for col in df.columns.tolist() if col.startswith('_var')]
df['special_mean'] = df[cols].mean(skipna=False, axis=1)

# or using @sammywemmy's method
df['special_mean'] = df.filter(like='_var').mean(skipna=False, axis=1)
  • Related