This is my data:
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)