遍历行并乘以预设行(kmeans)

2024-10-02 20:37:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用预设的数据帧重新创建k均值分析。目前,我正在尝试遍历数据帧的每一行(698行)并执行函数(row mu)**2,然后确定平方根。下面的步骤是将所述函数的平方根与我的2个簇(mu2或mu4)的平均值进行比较,以确定与该点的距离,并将该sqrt数分配给每个分类器,基于该分类器它更接近。。如果我指定要操作的两个mu参数是哪一行,那么我的函数可以正常工作:

A=[]
B=[]

mu2=df1.loc[5] #in this instance, mu2=(8,10,10,8,7,10,9,7,1)
mu4=df1.loc[245] #in this instance, mu4=(5,1,1,2,2,2,3,1,1)
specificrow=df1.loc[374] #in this instance, specificrow=(3,1,2,1,2,1,2,1,1)

def d(row, mu):
    sums=(row-mu)**2
    return math.sqrt(sums.sum())

mu2dist=d(specificrow, mu2)
mu4dist=d(specificrow, mu4)

if mu4dist<mu2dist:
    A.append(mu2dist)
else:
    B.append(mu4dist)

print(A, B)

这适当地增加了20.25到A

但是,如果我尝试将mu2和mu4分配给数据帧中的随机行:

mu2=df1.ix[np.random.choice(df.index, 1)]
mu4=df1.ix[np.random.choice(df.index, 1)]

相同的代码不起作用

for index, row in df1.iterrows():  
    mu2dist=d(row, mu2)
    mu4dist=d(row, mu4)

    if mu4dist<mu2dist:
        A.append(mu2dist)
    else:
        B.append(mu4dist)

print(A, B)

我得到一个错误,上面写着:

'TypeError: cannot convert the series to <class 'float'>'

回溯还引用了my d(row,mu)函数,尤其是这一行:

return math.sqrt(sums.sum())

我尝试使用.astype()将整个df转换为float,但仍然会遇到相同的错误。你知道吗

如果我打印mu2和它的类型(每次都有明显的变化),我会得到以下输出:

     A2   A3   A4   A5   A6   A7   A8   A9  A10
28  2.0  1.0  1.0  1.0  2.0  1.0  2.0  1.0  1.0 <class 
'pandas.core.frame.DataFrame'>

它看起来是float,但实际类型只是“pandas dataframe”。如果有人能指引我正确的方向,让这些金额返回/打印出来,我将不胜感激。我仍然需要研究如何保留这些值以重用,因为我多次重复此过程以找到最佳质心,但我需要首先获得这些值。你知道吗

谢谢


Tags: 数据函数insqrtthislocrowdf1