python - 我可以使用 lambda、map、apply 或 applymap 来填充数据框吗?

标签 python pandas dataframe

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

填充此数据框的最快方法是什么?我想尽可能地远离嵌套 for 循环(慢!)。我可以使用 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)

最佳答案

据我所知,与 for 循环相比,lambda 没有明显的速度优势 - 并且很难编写双 lambda,通常是为直接的行操作保留的。

然而,通过一些工程,我们可以将代码简化为几行简单且不言自明的代码:

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:

              25        36        70        95
target                                        
112     1.732051  0.000000  1.732051  3.464102
101     3.464102  1.732051  0.000000  1.732051
121     5.196152  3.464102  1.732051  0.000000
201     6.928203  5.196152  3.464102  1.732051

关于python - 我可以使用 lambda、map、apply 或 applymap 来填充数据框吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55113530/

相关文章:

r - 向缺少值的数据框添加行

Python计算每一行的MSE

python - 在 Python 中逐行组合多个文本文件

python - 通过 API 检索 GoogleDoc 并生成用自己的文本替换的 PDF

python - 如何编码趋势线角度

python - Pandas :如何获得第一个正数?

python - 对 pandas 数据框列执行多次转换

python - 如何通过python运行adb命令?

python - 划分数组Python的元素

python - Groupby 和示例 pandas