这就是我想要做的-我能够执行步骤1至4。

基本上,对于每个数据点,我想根据列y从所有均值向量中找到欧氏距离


取数据
分开非数值列
通过y列查找均值向量
保存方式
根据y值从每一行中减去每个均值向量
将每列平方
添加所有列
联接回数值数据集,然后联接非数值列


import pandas as pd

data = [['Alex',10,5,0],['Bob',12,4,1],['Clarke',13,6,0],['brke',15,1,0]]
df = pd.DataFrame(data,columns=['Name','Age','weight','class'],dtype=float)
print (df)
df_numeric=df.select_dtypes(include='number')#, exclude=None)[source]
df_non_numeric=df.select_dtypes(exclude='number')
means=df_numeric.groupby('class').mean()


对于means的每一行,从df_numeric的每一行中减去该行。然后在输出中每列取平方,然后为每一行添加所有列。然后将此数据重新连接到df_numericdf_non_numeric

-------------- update1

添加了如下代码。我的问题已更改,更新的问题在最后。

def calculate_distance(row):
    return (np.sum(np.square(row-means.head(1)),1))

def calculate_distance2(row):
    return (np.sum(np.square(row-means.tail(1)),1))


df_numeric2=df_numeric.drop("class",1)
#np.sum(np.square(df_numeric2.head(1)-means.head(1)),1)
df_numeric2['distance0']= df_numeric.apply(calculate_distance, axis=1)
df_numeric2['distance1']= df_numeric.apply(calculate_distance2, axis=1)

print(df_numeric2)

final = pd.concat([df_non_numeric, df_numeric2], axis=1)
final["class"]=df["class"]


谁能确认这是获得结果的正确方法?我主要关注最后两个声明。倒数第二条语句会正确连接吗?最终声明会分配原始的class吗?我想确认python不会以随机顺序进行concat和class分配,并且python将保持行出现的顺序

final = pd.concat([df_non_numeric, df_numeric2], axis=1)
final["class"]=df["class"]

最佳答案

我想这就是你想要的

import pandas as pd
import numpy as np
data = [['Alex',10,5,0],['Bob',12,4,1],['Clarke',13,6,0],['brke',15,1,0]]
df = pd.DataFrame(data,columns=['Name','Age','weight','class'],dtype=float)
print (df)
df_numeric=df.select_dtypes(include='number')#, exclude=None)[source]
# Make df_non_numeric a copy and not a view
df_non_numeric=df.select_dtypes(exclude='number').copy()

# Subtract mean (calculated using the transform function which preserves the
# number of rows) for each class  to create distance to mean
df_dist_to_mean =  df_numeric[['Age', 'weight']] - df_numeric[['Age', 'weight', 'class']].groupby('class').transform('mean')
# Finally calculate the euclidean distance (hypotenuse)
df_non_numeric['euc_dist'] = np.hypot(df_dist_to_mean['Age'], df_dist_to_mean['weight'])
df_non_numeric['class'] = df_numeric['class']
# If you want a separate dataframe named 'final' with the end result
df_final = df_non_numeric.copy()
print(df_final)


也许可以编写更密集的代码,但是通过这种方式,您将看到发生了什么。

关于python - 从多个均值向量中找到欧氏距离,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55148711/

10-09 03:35