我有一个如下所示的numpy数组。
array([[ 0.23810484, 0.00020161, 0.41350806, 0.2421371 , 0.02237903,
0.08084677, 0.00020161, 0.00221774, 0.00020161, 0.00020161],
[ 0.04279661, 0.05974576, 0.02584746, 0.00042373, 0.00042373,
0.00042373, 0.00042373, 0.73771186, 0.00889831, 0.12330508]])
是5000X10。
我还有一个Pandas Series对象,它又是5000长度。它的值是这样的>
5061 Terminated
17410 Completed Negative
共有三种不同的类别。每个系列值是第一个numpy数组中相应行的类别。
我想得到的是将第一个数组中每个变量的平均值按系列中的类别分组。所以最后我会得到一个numpy数组,每个类别的系列有3行,十列,其值将是所有5000行的平均值。
请告知
答案 0 :(得分:1)
您可以将numpy数组中的每一列添加到pandas DataFrame中的单独列,然后使用DataFrame.groupby()
根据所需列进行分组,然后执行mean()
。示例(假设您的系列称为系列,而numpy数组称为narray
) -
df = pd.DataFrame(series)
for i in range(10):
df[i] = narray[:,i]
df.groupby('required_column').mean()
演示 -
In [77]: df = pd.DataFrame([[5061,'Terminated'],[17410,'Completed Negative']],columns=['index','groupcol']).set_index('index')
In [78]: df
Out[78]:
groupcol
index
5061 Terminated
17410 Completed Negative
In [79]: x
Out[79]:
array([[ 2.38104840e-01, 2.01610000e-04, 4.13508060e-01,
2.42137100e-01, 2.23790300e-02, 8.08467700e-02,
2.01610000e-04, 2.21774000e-03, 2.01610000e-04,
2.01610000e-04],
[ 4.27966100e-02, 5.97457600e-02, 2.58474600e-02,
4.23730000e-04, 4.23730000e-04, 4.23730000e-04,
4.23730000e-04, 7.37711860e-01, 8.89831000e-03,
1.23305080e-01]])
In [80]: for i in range(10):
....: df[i] = x[:,i]
....:
In [81]: df
Out[81]:
groupcol 0 1 2 3 4 \
index
5061 Terminated 0.238105 0.000202 0.413508 0.242137 0.022379
17410 Completed Negative 0.042797 0.059746 0.025847 0.000424 0.000424
5 6 7 8 9
index
5061 0.080847 0.000202 0.002218 0.000202 0.000202
17410 0.000424 0.000424 0.737712 0.008898 0.123305
In [82]: df.groupby('groupcol').mean()
Out[82]:
0 1 2 3 4 \
groupcol
Completed Negative 0.042797 0.059746 0.025847 0.000424 0.000424
Terminated 0.238105 0.000202 0.413508 0.242137 0.022379
5 6 7 8 9
groupcol
Completed Negative 0.000424 0.000424 0.737712 0.008898 0.123305
Terminated 0.080847 0.000202 0.002218 0.000202 0.000202
如果您希望将结果作为列表,则可以 -
df.groupby('required_column').mean().values.tolist()
演示 -
In [83]: df.groupby('groupcol').mean().values.tolist()
Out[83]:
[[0.04279661,
0.05974576,
0.02584746,
0.00042373,
0.00042373,
0.00042373,
0.00042373,
0.73771186,
0.00889831,
0.12330508],
[0.23810484,
0.00020161,
0.41350806,
0.2421371,
0.02237903,
0.08084677,
0.00020161,
0.00221774,
0.00020161,
0.00020161]]