使用pandas数据帧行进行矩阵运算

Arn*_*old 5 python matrix dataframe pandas

我有一个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)
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

因此,我们的目标是每行large_haloes ['X_rot','Y_rot','Z_rot']应填充相应行的largest_haloes ['X','Y','Z']的旋转版本.如何在不循环遍历行的情况下执行此操作?我也试过df.dot,但是没有太多的文档,它似乎没有做我想要的.

Wan*_*der 2

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

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

lh = largest_haloes.values
rotated_array = lh.dot(rot)
Run Code Online (Sandbox Code Playgroud)

你也可以做

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