gpt4 book ai didi

python - 从散点图到二维数组

转载 作者:行者123 更新时间:2023-11-30 22:50:13 26 4
gpt4 key购买 nike

我的脑子在这件事上完全一片空白。

我想做我认为很简单的事情。

假设我有一些测试数据:

import pandas as pd
import numpy as np
k=10
df = pd.DataFrame(np.array([range(k),
[x + 1 for x in range(k)],
[x + 4 for x in range(k)],
[x + 9 for x in range(k)]]).T,columns=list('abcd'))

其中行对应时间,列对应角度,如下所示:

   a   b   c   d
0 0 1 4 9
1 1 2 5 10
2 2 3 6 11
3 3 4 7 12
4 4 5 8 13
5 5 6 9 14
6 6 7 10 15
7 7 8 11 16
8 8 9 12 17
9 9 10 13 18

然后由于我将其转换为并订购字典的原因:

def highDimDF2Array(df):
from collections import OrderedDict # Need to preserve order

vels = [1.42,1.11,0.81,0.50]

# Get dataframe shapes
cols = df.columns

trajectories = OrderedDict()
for i,j in enumerate(cols):
x = df[j].values
x = x[~np.isnan(x)]

maxTimeSteps = len(x)
tmpTraj = np.empty((maxTimeSteps,3))
# This should be fast
tmpTraj[:,0] = range(maxTimeSteps)
# Remove construction nans
tmpTraj[:,1] = x
tmpTraj[:,2].fill(vels[i])

trajectories[j] = tmpTraj

return trajectories

然后我把它全部绘制出来

import matplotlib.pyplot as plt
m = highDimDF2Array(df)
M = np.vstack(m.values())
plt.scatter(M[:,0],M[:,1],15,M[:,2])
plt.title('Angle $[^\circ]$ vs. Time $[s]$')
plt.colorbar()
plt.show()

enter image description here

现在我想做的就是将所有这些放入具有以下属性的 2D numpy 数组中:

  • 时间映射到 x 轴(或者 y 轴并不重要)
  • 角度映射到 y 轴
  • 矩阵中的条目对应于散点图中彩色点的值
  • 所有其他条目均被视为 NaN(即散点图中未由点定义的条目)

在 3D 中,颜色将对应于高度。

我正在考虑使用这样的东西:3d Numpy array to 2d但我不太确定如何。

最佳答案

您可以将 M[:,1] 和 M[:,2] 中的值转换为整数,并将它们用作 2D numpy 数组的索引。以下是使用您定义的 M 值的示例。

out = np.empty((20,10))
out[:] = np.NAN
N = M[:,[0,1]].astype(int)
out[N[:,1], N[:,0]] = M[:,2]
plt.scatter(M[:,0],M[:,1],15,M[:,2])
plt.scatter(M[:,0],M[:,1],15,M[:,2])
plt.title('Angle $[^\circ]$ vs. Time $[s]$')
plt.colorbar()
plt.imshow(out, interpolation='none', origin = 'lower')

enter image description here

在这里,您可以直接将 M 转换为整数,但您可能必须想出一个函数来将 M 的列映射为整数,具体取决于您正在创建的数组的分辨率。

关于python - 从散点图到二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39475146/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com