【发布时间】:2020-02-18 12:25:18
【问题描述】:
如果值是数字,我想在 pandas 数据框中找到列的平均值,如果值是分类值,我想找到系列的模式。我只想使用我称之为“meanmode”的一个变量来做到这一点。
当我尝试以下操作时:
def mean_mode(val):
return meanmode = val.mean() if val.dtype != 'object' else val.mode()[0]
我得到错误:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
我如何为变量“meanmode”分配其各自的平均值(如果是数值)和模式(如果是分类)?
到目前为止我的代码:
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
【问题讨论】:
-
val是数据框、系列还是什么? -
Val 是一个数据框。从该数据帧中,此代码提取要在 qualitydf(输出数据帧)中显示给用户的特征。虽然所有代码都可以正常工作,但我被困在 meanmode 问题上。
标签: python pandas variables mean mode