将函数应用于 Pandas Python 中的每一行时发生数据转换错误 [英] Data Conversion Error while applying a function to each row in pandas Python
问题描述
我在 python 中的 Pandas 中有一个数据框,它类似于这样的东西 -
I have a data frame in pandas in python which resembles something like this -
contest_login_count contest_participation_count ipn_ratio
0 1 1 0.000000
1 3 3 0.083333
2 3 3 0.000000
3 3 3 0.066667
4 5 13 0.102804
5 2 3 0.407407
6 1 3 0.000000
7 1 2 0.000000
8 53 91 0.264151
9 1 2 0.000000
现在我想对这个数据框的每一行应用一个函数函数是这样写的 -
Now I want to apply a function to each row of this dataframe The function is written as this -
def findCluster(clusterModel,data):
return clusterModel.predict(data)
我以这种方式将此函数应用于每一行 -
I apply this function to each row in this manner -
df_fil.apply(lambda x : findCluster(cluster_all,x.reshape(1,-1)),axis=1)
当我运行此代码时,我收到一条警告说 -
When I run this code, I get a warning saying -
DataConversionWarning:具有输入 dtype 对象的数据已转换为 float64.
DataConversionWarning: Data with input dtype object was converted to float64.
warnings.warn(msg, DataConversionWarning)
warnings.warn(msg, DataConversionWarning)
此警告每行打印一次.因为,我的数据框中有大约 450K 行,所以我的计算机在 ipython 笔记本上打印所有这些警告消息时挂起.
This warning is printed once for each row. Since, I have around 450K rows in my data frame, my computer hangs while printing all these warning messages that too on ipython notebook.
但是为了测试我的功能,我创建了一个虚拟数据框并尝试对其应用相同的功能,并且效果很好.这是代码 -
But to test my function I created a dummy dataframe and tried applying the same function on that and it works well. Here is the code for that -
t = pd.DataFrame([[10.35,100.93,0.15],[10.35,100.93,0.15]])
t.apply(lambda x:findCluster(cluster_all,x.reshape(1,-1)),axis=1)
输出结果是 -
0 1 2
0 4 4 4
1 4 4 4
任何人都可以建议我做错了什么,或者我可以改变什么来消除这个错误?
Can anyone suggest what am I doing wrong or what can I change to make this error go away?
推荐答案
我觉得有些列的dtype
不是float
有问题.
I think there is problem dtype
of some column is not float
.
你需要通过 astype
:
You need cast it by astype
:
df['colname'] = df['colname'].astype(float)
这篇关于将函数应用于 Pandas Python 中的每一行时发生数据转换错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!