如何忽略python中.csv文件中的Nan?

问题描述

我在读取 .csv 文件的列时遇到问题。我有这个代码

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler


# Importing the dataset
dataset = pd.read_csv('D:/CTU/ateroskleroza/development/results_output6.csv')
print(dataset.head())


X = dataset.iloc[:,2:16].values
y = dataset.iloc[:,0].values


# Splitting the dataset into the Training set and Test set

X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.25)

classifier = make_pipeline(StandardScaler(),SVC(gamma='auto'))
classifier.fit(X_train,y_train)

y_pred = classifier.predict(X_test)

# Making the Confusion Matrix

cm = confusion_matrix(y_test,y_pred)
print(cm)
# Generating accuracy,precision,recall and f1-score

target_names = ['Progressive','Stable']
print(classification_report(y_test,y_pred,target_names=target_names))

.csv 看起来像这样:

enter image description here

enter image description here

根据图片名称,他们有一些栏目,其他一些与Nan有关。问题是当我尝试执行此代码时出现此错误

ValueError: Input contains NaN,infinity or a value too large for dtype('float64').

那么我怎么能忽略Nan而只使用数字呢? (我不想删除空列,只是在执行时忽略 Nan)。

解决方法

我是根据个人经验写这个答案的。如果您想要更详细的答案,请考虑使用我们可以使用的数据集更新您的帖子,说明模型应该预测什么并描述特征。

@simpleApp 建议在缩放数据和拟合模型之前用零替换空值。在评论中,您似乎担心将空值归入最终模型的影响。

在处理缺失数据时,您必须权衡插补值的利弊。如果您决定忽略具有空值的观测值(通过删除列或整个观测值),您可能会错过一些非常重要的信息,并且您将无法对新观测值进行预测,除非它们的数据完全满了。同样,如果您不小心将一些随机值归入空值,则可能会给模型引入偏差。

如果您正确估算值,您的模型将能够处理缺失的数据,而不会影响其大部分准确性。可悲的是,估算价值与其说是一门硬科学,不如说是一门艺术。

我不知道您的数据意味着什么,但可以将年龄视为预测心脏病风险的独立变量。问问自己:如果缺少某个值,我是最好忽略观察结果,还是可以用一个值来填补空白,该值平均而言不应与患者未观察到的真实年龄相差太远?

如果你决定用一些值填充缺失的信息,我会推荐四种非常简单的方法:

# Fill with minimum value
df = df.fillna(df.mean(),axis=1)

# Fill with median value
df = df.fillna(df.median(),axis=0)

# Fill with mean value
df = df.fillna(df.mean(),axis=0)

# Fill with maximum value
df = df.fillna(df.max(),axis=0)

您的下一步应该是对结果模型进行评分,并选择最能概括未知数据的模型。

在其他常见的插补技术中,您可以用零 (df.fillna(0))、最频繁的值(检查 SimpleImputer)或更复杂的插补技术,例如 {{3} }.

最后,当您在看不见的数据上测试模型的性能时,您会发现插补空值是否正确。

作为一般经验法则,您应该考虑删除缺失值超过 20% 的所有列。