Pandas操作导致sklearn auc函数出错

问题描述

我正在尝试从 .txt 文件中读取一些信息,然后对这些数据使用 sklearn auc 函数。 .txt 文件是字符串、整数和浮点数的混合体,顶部还有一些我没有用的行以及一些空白行。因此需要进行一些预处理才能将其转换为可用的数据帧。如果我手动清理文本文件,下面的代码运行成功。

import pandas as pd
from sklearn.metrics import auc

# Read the data and drop the NaN column produced at the end
fp = r"(<full file path to cleaned file>.txt"
df = pd.read_csv(fp,delimiter = '\t')
df.dropna(axis = 1,inplace=True)

# Convert the first and second columns to numpy ndarrays
kk_array = df.iloc[:,2].to_numpy()
MM_array = df.iloc[:,1].to_numpy()

# Calculate the area under the curve 
print(auc(kk_array,MM_array))

当我尝试使用 Pandas 进行清理时,出现以下错误

  File "...\Anaconda3\lib\site-packages\numpy\lib\function_base.py",line 1269,in diff
    a = op(a[slice1],a[slice2])

TypeError: unsupported operand type(s) for -: 'str' and 'str'

代码如下:

import pandas as pd
from sklearn.metrics import auc

# Read the data ignoring the blank rows and data about the file near the top.
fp = r"<full file path to raw file>.txt"
df = pd.read_csv(fp,delimiter = '\t',skiprows=[0,1,2,3,4,5,6,7,8,9,11,15])
df.dropna(axis = 1,inplace=True)

# Combine the string columns in the first 4 rows into one and make that the header.
list_a = list(df) # this returns a list of the headers
list_b = list(df.iloc[0])
list_c = list(df.iloc[1])
list_d = list(df.iloc[2])
new_header_list = [a + "/" + b + "/" + c + "/" + d for a,b,c,d in zip(list_a,list_b,list_c,list_d)]

# Now drop the redundant rows and change the header.
df = df[3:]
df.columns = new_header_list

# Convert the first and second columns to numpy ndarrays
kk_array = df.iloc[:,MM_array))

现在,显然我的问题是 kk_array 和 MM_array 被解释为字符串。在我第一个有效的代码片段中,kk_array 和 MM_array 的类型是“float64 数组”,但不起作用的代码是“对象数组”类型。

我尝试了一些方法来强制它们成为浮点数,例如 df.apply(pd.to_numeric) 但似乎没有任何效果。有人可以帮我了解发生了什么问题吗?

谢谢

解决方法

无耻地从上面的评论中复制以供其他人将来参考:

您可以在 pd.to_numpy() 中指定数据类型。尝试传递 dtype=np.float32 或其他一些数字变量,看看问题是否仍然存在。请参阅:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html