python - 在 pandas 中合并列的更有效方法

标签 python pandas numpy

我的代码计算我拥有的一组样本中所有点之间的欧几里德距离。我想知道的是,一般来说,这是在集合中的所有元素之间执行某些操作然后绘制它们的最有效方法,例如制作相关矩阵。

样本索引用于初始化数据帧并提供标签。然后,3d 坐标以三元组形式提供,但这可以很容易地是任何测量,然后可变距离可以是任何操作。我很好奇找到一种更有效的解决方案来制作每一列,然后使用 pandas 或 numpy 再次合并它们。我的解决方案是否堵塞了内存?我怎样才能使它更干净?

def euclidean_distance_matrix_maker(three_D_coordinate_tuple_list, index_of_samples):
#list of tuples
#well_id or index as series or list

n=len(three_D_coordinate_tuple_list)
distance_matrix_df=pd.DataFrame(index_of_samples)    

for i in range(0, n):
    column=[]
    #iterates through all elemetns calculates distance vs this element
    for j in range(0, n):
        distance=euclidean_dist_threeD_for_tuples( three_D_coordinate_tuple_list[i],
                                         three_D_coordinate_tuple_list[j])
        column.append(distance)
    #adds euclidean distance to a list which overwrites old data frame then 
    #is appeneded with concat column wise to output matrix
    new_column=pd.DataFrame(column)
    distance_matrix_df=pd.concat([distance_matrix_df, new_column], axis=1)

distance_matrix_df=distance_matrix_df.set_index(distance_matrix_df.iloc[:,0])
distance_matrix_df=distance_matrix_df.iloc[:,1:]
distance_matrix_df.columns=distance_matrix_df.index

最佳答案

设置

import numpy as np

x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
<小时/>

scipy.spatial.distance_matrix

from scipy.spatial import distance_matrix

distance_matrix(x, x)

array([[ 0.        ,  5.19615242, 10.39230485],
       [ 5.19615242,  0.        ,  5.19615242],
       [10.39230485,  5.19615242,  0.        ]])
<小时/>

Numpy

from scipy.spatial.distance import squareform

i, j = np.triu_indices(len(x), 1)
((x[i] - x[j]) ** 2).sum(-1) ** .5

array([ 5.19615242, 10.39230485,  5.19615242])

我们可以用squareform将其制作成正方形

squareform(((x[i] - x[j]) ** 2).sum(-1) ** .5)

array([[ 0.        ,  5.19615242, 10.39230485],
       [ 5.19615242,  0.        ,  5.19615242],
       [10.39230485,  5.19615242,  0.        ]])

关于python - 在 pandas 中合并列的更有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59724139/

相关文章:

python - Order by 可以与模型中的属性一起使用吗?

python - 如何在python中指定时间后自动关闭mysql连接?

python - 测试 pandas DataFrame 是否存在

python - df.hist() 与 df.plot.hist()?

python - 查找边界之间错误颜色的像素

python - 在 pandas 数据框中使用文本字符串数据进行条件数据选择

python - 这个错误是什么意思 : ValueError: renderer was passed non-dictionary as value

python - 合并 Pandas 2 DataFrame,具有不同的行数和列数

python - 在 Panda Dataframe 中附加 bool 列

python - 使用 numpy.savetxt 导出数组时在每行前添加注释