Python 在数据帧上迭代时向其添加元素

Python 在数据帧上迭代时向其添加元素,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个名为SBPV_DBPV的数据框架,看起来像这样: STUDY_ID SBPV DBPV 0 1 12.927571 19.054308 1 3 12.635492 10.603099 2 5 25.825786 7.663226 3 6 16.931817 12.369440 我试图手动实现KMeans算法。所以我有3个质心,我试图计算每行到这些质心的距离,并将最小质心附加到数据帧中的行

我有一个名为
SBPV_DBPV
的数据框架,看起来像这样:

    STUDY_ID    SBPV    DBPV
0   1        12.927571  19.054308
1   3        12.635492  10.603099
2   5        25.825786  7.663226
3   6        16.931817  12.369440
我试图手动实现KMeans算法。所以我有3个质心,我试图计算每行到这些质心的距离,并将最小质心附加到数据帧中的行:

for i, row in SBPV_DBPV.iterrows():
    #distance of each row to the 3 centroids
    dist1 = ((row['SBPV'] - (k1.values.reshape(-1,1)[0]))**2 + (row['DBPV'] - k1.values.reshape(-1,1)[1])**2)**0.5
    dist2 = (row['SBPV'] - (k2.values.reshape(-1,1)[0])**2 + (row['DBPV'] - k2.values.reshape(-1,1)[1])**2)**0.5 
    dist3 = (row['SBPV'] - (k3.values.reshape(-1,1)[0])**2 + (row['DBPV'] - k3.values.reshape(-1,1)[1])**2)**0.5 
    row['cluster'] = min(dist1,dist2,dist3)
但是,在我运行循环之后,数据帧不会被修改。我已经读到,我必须使用
.apply
来修改数据帧,但我不知道如何在迭代行时实现这一点

谢谢

您需要更改:

row['cluster'] = min(dist1,dist2,dist3)
致:

用于按索引值赋值

SBPV_DBPV.loc[i, 'cluster'] = min(dist1,dist2,dist3)