我想创建一个函数来计算选定类别与数据集中所有其他类别之间的曼哈顿距离。该函数应该返回与选定类别距离最小的类别。
df = pd.DataFrame(np.random.randint(0,100, size= (10,4)), columns=list('ABCD'))df['category']= ['apple','orange','grape','berry','strawberry','banana','kiwi','lemon','lime','pear']
下面的代码返回了包括选定类别在内的最小的4个距离(距离为0的选定类别是多余且不需要的)。我需要代码只返回最小的3个距离作为类别列表,第一个是距离最小的类别。
def distance(row): cols = list('ABCD') return (df[cols] - row[cols]).abs().sum(axis=1)df.set_index('category', inplace=True)dist = df.apply(distance, axis=1)dist['apple'].nsmallest(4)
例如,如果选择了“Apple”,并且从Apple到Berry、Orange和Grape的三个最低距离分别是最低的,那么返回结果应如下所示:[“Berry”, “Orange”,”Grape”]
回答:
一种选择是使用scipy.spatial.distance
中的cityblock
函数:
from scipy.spatial import distancedf.set_index('category', inplace = True)>> df.apply(lambda x: distance.cityblock(x, df.loc['apple',:]), axis=1 ).drop('apple', axis=1).nsmallest(4).index.values.tolist() ['strawberry', 'berry', 'kiwi', 'orange']
基本上,你可以得到每一行到选定行的距离。然后你删除包含选定标签的行,并选择最小的距离的索引。