根据按键阵列重塑 [英] Array reshaped according to keys
问题描述
我不知道什么我希望做确切的技术术语,所以我会试着用一个例子证明:
I don't know the exact technical terms for what I wish to do, so I'll try and demonstrate with an example:
我有两个向量的长度相同,的 A 和乙的,如下:
I have two vectors the same length, a and b, as below:
In [41]:a
Out[41]:
array([ 0.61689215, 0.31368813, 0.47680184, ..., 0.84857976,
0.97026244, 0.89725481])
In [42]:b
Out[42]:
array([35, 36, 37, ..., 36, 37, 38])
的在的有N个浮点数和乙的有n个元素:与10个不同值的键:35,36,37,...,43,44
a contains N floating point numbers and b contains N elements: keys with 10 distinct values: 35, 36, 37, ..., 43, 44
我希望得到一个新的矩阵的 M 的有10列,其中第一列包含的在的所有行的相应键的乙 35是在第二列的 M 的包含所有行的在的,其相应的键的乙的是36等都达列10的 M 的
I wish to get a new matrix M that has 10 columns where the first column contains all the rows in a whose corresponding key in b is 35. The second column in M contains all the rows in a whose corresponding key in b is 36. Etc. all up to column 10 in M.
我希望这是显而易见的。谢谢
I hope this was clear. Thank you
推荐答案
您可以用熊猫:
import numpy as np
import pandas as pd
a = np.random.rand(50)
b = np.random.randint(10, 15, 50)
s = pd.Series(a)
s.groupby(b).apply(pd.Series.reset_index, drop=True).unstack(level=0)
的输出是:
10 11 12 13 14
0 0.465079 0.041393 0.692856 0.634328 0.179690
1 0.934678 0.746048 0.060014 0.072626 0.824729
2 0.388190 0.510527 0.078662 0.077157 0.291183
3 0.972033 0.761159 0.017317 0.104768 0.278871
4 0.750713 0.430246 0.083407 0.262037 0.487742
5 0.216965 0.482364 0.820535 0.207008 0.276452
6 0.282038 0.607303 0.675856 0.994369 0.602059
7 0.897106 0.398808 0.312332 0.751388 0.878177
8 0.229121 NaN NaN 0.061288 0.032066
9 0.810678 NaN NaN NaN 0.718237
10 0.571125 NaN NaN NaN 0.668292
11 0.410750 NaN NaN NaN 0.288145
12 0.984507 NaN NaN NaN NaN
这篇关于根据按键阵列重塑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!