我想创建一个函数来计算数据集中选定类别与所有其他类别之间的曼哈顿距离。然后,该函数应返回与所选距离最短的 CATEGORY。
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"]
请您参考如下方法:
设置:
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']
df.set_index('category', inplace = True)
这是一口但是:
lowest_3 = [df.index[pd.Series([abs(df.loc[ind1] - df.loc[ind2]).sum() for ind2 in df.index]).argsort()[1:4]].tolist() for ind1 in df.index]
lowest_3_series = pd.Series(lowest_3, index = df.index)
lowest_3_series['apple'] = ['banana', 'lemon', 'grape'] # Results will differ due to randomness obviously
这将为您提供 df.index 中每个值的最低 3 个值的列表。
例如,此列表的第一个元素是您对 'apple'
解释:
首先,您为 df.index 中的每个索引创建一个列表理解。这个嵌套列表理解是对 df.index 的再次迭代。您为此索引调用 df 并将它们全部成对比较(总共进行 n^2 次比较)。您通过取列值之间的绝对值并将它们相加来比较每个索引。然后将这个列表变成一个系列,并使用 argsort 获取前 3 个(不包括始终为 0 的自反比较)。然后你在这个索引切片上调用 df.index,它会为你提供这 3 个最低值的名称。
