【问题标题】:Matrix operations with rows of pandas dataframes具有熊猫数据框行的矩阵运算
【发布时间】:2016-10-13 21:27:03
【问题描述】:

我有一个 pandas 数据框,其中包含对应于对象位置的 x、y 和 z 坐标的三列。我还有一个转换矩阵,可以将这些点旋转一定角度。我之前遍历了执行此转换的数据帧的每一行,但我发现这非常非常耗时。现在我只想一次执行所有转换并将结果附加为附加列。

我正在寻找这条线的工作版本(它总是返回形状不匹配):

largest_haloes['X_rot', 'Y_rot', 'Z_rot'] = np.dot(rot,np.array([largest_haloes['X'], largest_haloes['Y'], largest_haloes['Z']]).T)

这是一个最小的工作示例:

from __future__ import division
import math
import pandas as pd
import numpy as np

def unit_vector(vector):
    return vector / np.linalg.norm(vector)


largest_haloes = pd.DataFrame()
largest_haloes['X'] = np.random.uniform(1,10,size=30)
largest_haloes['Y'] = np.random.uniform(1,10,size=30)
largest_haloes['Z'] = np.random.uniform(1,10,size=30)

normal = np.array([np.random.uniform(-1,1),np.random.uniform(-1,1),np.random.uniform(0,1)])
normal = unit_vector(normal)

a = normal[0]
b = normal[1]
c = normal[2]

rot = np.array([[b/math.sqrt(a**2+b**2), -1*a/math.sqrt(a**2+b**2), 0], [(a*c)/math.sqrt(a**2+b**2), b*c/math.sqrt(a**2+b**2), -1*math.sqrt(a**2+b**2)], [a, b, c]])

largest_haloes['X_rot', 'Y_rot', 'Z_rot'] = np.dot(rot,np.array([largest_haloes['X'], largest_haloes['Y'], largest_haloes['Z']]).T)

所以目标是 maximum_haloes['X_rot', 'Y_rot', 'Z_rot'] 的每一行都应该填充相应行 maximum_haloes['X','Y','Z' 的旋转版本]。如何在不循环行的情况下做到这一点?我也尝试过 df.dot 但没有太多文档,而且它似乎没有达到我想要的效果。

【问题讨论】:

    标签: python pandas matrix dataframe


    【解决方案1】:

    如果您的意思是通过旋转进行矩阵乘法。

    您可以将两者都转换为 numpy 数组并将其执行为

    lh = largest_haloes.values
    rotated_array = lh.dot(rot)
    

    你也可以这样做

    x = pd.DataFrame(data=rot,index=['X','Y','Z'])
    rotated_df = largest_haloes.dot(x)
    

    【讨论】:

    • 这成功了!然而,我花了一段时间才意识到,通过旋转矩阵的属性,np.dot(rot, point.T) 旋转了相同的角度,但与 np.dot(point, rot) 的方向相反。所以我使用了你的第一个建议,但改变了参数的顺序以获得我需要的东西。
    猜你喜欢
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 2021-10-02
    • 2018-11-09
    • 2020-12-15
    相关资源
    最近更新 更多