【发布时间】: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