我可以使用lambda,map,apply或applymap填充数据框吗?

时间:2019-03-12 03:06:58

标签: python pandas dataframe

这是我的数据的简化版本。我有一个坐标数据框,一个空的数据框,应使用提供的函数填充每一对的距离。

填充此数据框的最快方法是什么?我想尽可能地避免嵌套循环(慢!)。我可以使用apply或applymap吗? 您可以相应地修改功能或其他部分。谢谢。

import pandas as pd

def get_distance(point1, point2):
    """Gets the coordinates of two points as two lists, and outputs their distance"""
    return (((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2 + (point1[2] - point2[2]) ** 2) ** 0.5)

#Dataframe of coordinates.    
df = pd.DataFrame({"No.": [25, 36, 70, 95, 112, 101, 121, 201], "x": [1,2,3,4,2,3,4,5], "y": [2,3,4,5,3,4,5,6], "z": [3,4,5,6,4,5,6,7]})
df.set_index("No.", inplace = True)

#Dataframe to be filled with each pair distance.
df_dist = pd.DataFrame({'target': [112, 101, 121, 201]}, columns=["target", 25, 36, 70, 95])
df_dist.set_index("target", inplace = True)

2 个答案:

答案 0 :(得分:0)

如果不想用于循环,则可以通过以下方式计算所有可能的对之间的距离。

首先需要对df进行笛卡尔乘积运算,以得到所有可能的点对。

i, j = np.where(1 - np.eye(len(df)))
df=df.iloc[i].reset_index(drop=True).join(
    df.iloc[j].reset_index(drop=True), rsuffix='_2')

其中ij是大小为len(df)的方阵的上下三角形的布尔索引。完成此操作后,您只需要应用距离功能

df['distance'] = get_distance([df['x'],df['y'],df['z']], [df['x_2'],df['y_2'],df['z_2']])
df.head()

No. x   y   z   No._2   x_2 y_2 z_2 distance
0   25  1   2   3   36  2   3   4   1.732051
1   25  1   2   3   70  3   4   5   3.464102
2   25  1   2   3   95  4   5   6   5.196152
3   25  1   2   3   112 2   3   4   1.732051
4   25  1   2   3   101 3   4   5   3.464102

如果只想计算df_dist中的点,则可以相应地修改矩阵1 - np.eye(len(df))

答案 1 :(得分:0)

AFAIK与for循环相比,lambda并没有明显的速度优势-很难编写双lambda,通常保留给直接的行操作。

但是,通过一些工程设计,我们可以将代码简化为一些简单的自我解释的行:

    <select
      class="form-control"
      (change)="onSelectPageSize($event.target.value)"
      [ngModel]="pageSize"
    >

      <option *ngFor="let size of pageSizeOptions; let i = index" [ngValue]="size">
        {{ size }}
      </option>
    </select>

产生的import numpy as np get = lambda i: df.loc[i,:].values dist = lambda i, j: np.sqrt(sum((get(i) - get(j))**2)) # Fills your df_dist for i in df_dist.columns: for j in df_dist.index: df_dist.loc[j,i] = dist(i, j)

df_dist
相关问题