在数据帧上使用R.dot(向量)

2024-03-29 08:45:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了一个数据帧,包含x,y,z方向上多个实体的数据,时间作为索引,类似于:

df = pd.DataFrame(index=range(0,10), columns=pd.MultiIndex.from_tuples([("foo","x"),("foo","y"),("foo","z"),("bar","x"),("bar","y"),("bar","z")]), data=np.random.rand(10,6))
        foo                           bar                    
          x         y         z         x         y         z
0  0.972557  0.711319  0.190318  0.134453  0.903132  0.847353
1  0.922516  0.369936  0.940566  0.847049  0.180356  0.925252
2  0.843484  0.817282  0.245280  0.614433  0.959601  0.571053
3  0.409911  0.643583  0.723806  0.652375  0.532277  0.278601
4  0.322778  0.270078  0.822233  0.224622  0.808430  0.786399
5  0.323539  0.009899  0.175882  0.897813  0.287025  0.648503
6  0.180822  0.199223  0.573267  0.739941  0.479798  0.048885
7  0.961212  0.085247  0.092500  0.629304  0.582119  0.788289
8  0.960532  0.558652  0.676768  0.235705  0.255208  0.232676
9  0.213508  0.042688  0.238658  0.685202  0.760240  0.860439

我需要做的是对每个实体使用不同的旋转矩阵来旋转x,y,z数据,并用新值替换旧值。目前对每个索引都是这样做的:

for entity in df.columns.levels[0]:
    R = np.matrix("[-0.70710678,-0.70710678,0.];[0.70710678,-0.70710678,0.];[0.,0.,1.]")
    for row in df.index:
                try:
                    vector = np.array(
                        [[df.loc[row, (entity, x)]], [df.loc[row, (entity, y)]], [df.loc[row, (entity, z)]]])
                    rvector = R.dot(vector)
                    df.loc[row, (entity, x)] = complex(rvector[0])
                    df.loc[row, (entity, y)] = complex(rvector[1])
                    df.loc[row, (entity, z)] = complex(rvector[2])
                except ValueError as e:
                    logger.error(e)
                    logger.debug(f"{vector} {R} {row}")

我试着想出一个更简单/更快的方法。我得到了一个包含174个实体和1255个时间步的数据帧,按照我目前的实现,一个实体的计算大约需要1分钟。三根柱子同时工作的地方,但我能想出来

编辑:添加示例矩阵


Tags: 数据实体dfindexfoonp时间bar
1条回答
网友
1楼 · 发布于 2024-03-29 08:45:57

所以,经过更多的尝试,我们找到了一个解决方案:

    entity_data = df.loc[:, entity]
    data = R.dot(entity_data.transpose()).transpose()
    entity_data_new = pd.DataFrame(data=data, index=entity_data.index,
                                   columns=entity_data.columns)
    df.loc[:, entity] = entity_data_new.values

这将把计算时间减少到近似线性时间

相关问题 更多 >