mode() 调用在 scipy/numpy 中无法按预期工作



我在Windows 10中运行Python 3.6。

我正在使用此处的火车数据:https://datahack.analyticsvidhya.com/contest/practice-problem-loan-prediction-iii/

我尝试计算列的模式。 我的代码是:

from scipy.stats import mode
import pandas as pd
data = pd.read_csv('Loan3_train.csv')
mode(data['Gender'])[0]
This returns a warning and an exception:
C:ProgramDataAnaconda3libsite-packagesscipystatsstats.py:253: RuntimeWarning: The input array could not be properly checked for nan values. nan values will be ignored.
"values. nan values will be ignored.", RuntimeWarning)
TypeError: '>' not supported between instances of 'str' and 'float'

如何理解并解决这些消息?

这是一个数据类型不匹配错误!模式要求列为浮点数,而您传递的是字符串。使用 astype 将浮点数转换为 str,就像data['Gender'] = data['Gender'].astype(float)一样

从错误来看,某些数据是非数字的。 其中也可能有空值。

您需要查找非数字数据的示例并处理这些示例。

您可以使用df.applymap(np.isreal)来查找问题。 当你有冒犯字符串时,如果可能的话,你需要考虑一个映射到这些字符串以使它们成为数字。

或者,如果您发现您有类似"3+"或类似数据的数据,您可以将其处理astype('category')以查找模式,前提是您没有空值。

最新更新