如何将numpy数组分成pandas中的单独列

时间:2016-09-28 19:32:36

标签: python pandas numpy

我的数据框看起来像

  ID_0 ID_1  ID_2
0    a    b  0.05
1    a    b  0.10
2    a    b  0.19
3    a    c  0.25
4    a    c  0.40
5    a    c  0.65
6    a    c  0.71
7    d    c  0.95
8    d    c  1.00

我想分组并为每个组制作ID_2列的标准化直方图。所以我做了

df.groupby(['ID_0', 'ID_1']).apply(lambda x: np.histogram(x['ID_2'], range = (0,1), density=True)[0]).reset_index(name='ID_2')

然而,我真正想要的是numpy数组的11个元素位于数据帧的不同列中。

我该怎么做?

1 个答案:

答案 0 :(得分:3)

您可以从每个numpy数组构造一个系列对象,这些元素将作为列广播:

import pandas as pd
import numpy as np
df.groupby(['ID_0', 'ID_1']).apply(lambda x: pd.Series(np.histogram(x['ID_2'], range = (0,1), density=True)[0])).reset_index()

enter image description here