I want to find the mean of a column in a pandas dataframe if the value is numerical and find the mode of the series if the values are categorical. I only want to do this using one variable I call 'meanmode'.
When I try the following:
def mean_mode(val):
return meanmode = val.mean() if val.dtype != 'object' else val.mode()[0]
I get the error:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
How can I assign the variable 'meanmode' its respective values of mean if numerical and mode if categorical?
My Code so far:
def report(val):
dtypes = val.dtypes
rows = val.T.apply(lambda x: x.count(), axis=1)
nuniq = val.T.apply(lambda x: x.nunique() , axis=1)
uniq = val.T.apply(lambda x: x.unique() if x.dtype == 'object' else None, axis=1)
total = val.T.apply(lambda x: x.isna().sum(), axis=1)
count = val.shape[0]
pc = np.round(total / count * 100, 2)
mini = val.min()
maxi = val.max()
meanmode = val.apply(lambda x: x.mode()[0] if x.dtype == 'object' else mean(val))
qualitydf = pd.concat([dtypes, rows, total, pc, meanmode, mini, maxi, nuniq, uniq],
keys=['Dtype', 'Available Rows', 'Missing Values',
'Percent Missing', 'Mean-Mode',
'Min', 'Max',
'No. Of Uniques', 'Unique Values'], axis=1)
return qualitydf