应用Groupby后,根据不同的列值选择列值

时间:2015-06-15 00:17:44

标签: python group-by dataframe

我可以让这个工作,但不是在我申请groupby之后。在这个例子中,我只想让最后一列包含x列中的最低值。我用一个名为yminx的列来弹出df,这就是我希望我的abc列看起来像。我无法将abc的值变为本地(在groupby之后)min。

In [3]:

df
Out[3]:
   Symbol   x   y  yminx
0     IBM  12  27     58
1     IBM   1  58     58
2     IBM  13  39     58
3     IBM   4  45     58
4      GS   5  72     44
5      GS  15  54     44
6      GS  20  50     44
7      GS   4  90     44
8      GS  14  39     44
9      GS   2  44     44
10     GS   7  79     44
11     GS  12  27     44
12     GS  11  66     44

df['try']=df.groupby(['Symbol'])['x'].transform('min')
df['cond1'] = df['x'] == min(df['x'])                     
df['abc']= np.select(df['cond1'],df['y'])


    Symbol   x   y  yminx  cond1  abc  try
0     IBM  12  27     58  False   58    1
1     IBM   1  58     58   True   58    1
2     IBM  13  39     58  False   58    1
3     IBM   4  45     58  False   58    1
4      GS   5  72     90  False   58    2
5      GS  15  54     90  False   58    2
6      GS  20  50     90  False   58    2
7      GS   4  90     90  False   58    2
8      GS  14  39     90  False   58    2
9      GS   2  44     90  False   58    2
10     GS   7  79     90  False   58    2
11     GS  12  27     90  False   58    2
12     GS  11  66     90  False   58    2

在输出中,我看到58被选中,这是IBM的nin,但是当我到达GS时,同样的分钟被转移,好像从未引用过groupby一样

我确信这只是一种语法问题,但我被卡住了。

感谢您的帮助

约翰

1 个答案:

答案 0 :(得分:0)

一种方法是使用最小值的 indices 。例如:

>>> imin = df.groupby("Symbol")["x"].transform("idxmin")
>>> df["yminx"] = df.loc[imin, "y"].values
>>> df
   Symbol   x   y  yminx
0     IBM  12  27     58
1     IBM   1  58     58
2     IBM  13  39     58
3     IBM   4  45     58
4      GS   5  72     44
5      GS  15  54     44
6      GS  20  50     44
7      GS   4  90     44
8      GS  14  39     44
9      GS   2  44     44
10     GS   7  79     44
11     GS  12  27     44
12     GS  11  66     44

values是必需的,因为df.loc的结果有自己的索引,我们想忽略它,而只关心值。)