pandas 数据框:按另一列分组后获取列的最大值
pandas data frame: get maxima of a column after grouping by another coumn
我尝试为每个 A 获得最大的 B。 C 和 D 在那里,因为我的数据集不仅仅是我想要排序并获得最大值的 2 列。
import pandas
import numpy
df = pandas.DataFrame({'A': [10, 10, 20, 20, 30, 20, 10, 20],
'B': [1001, 1002, 2002, 2003, 3001, 2003, 1002, 2003],
'C': numpy.random.randn(8),
'D': numpy.random.randn(8)})
像这样:
df[['A', 'B']].somepandas(magic)
期望的结果是:
B
A
10 1002
20 2003
30 3001
但到目前为止我只知道在不分组的情况下获取每列的最大值:
df[['A', 'B']].max(axis=0)
A 30
B 3001
dtype: int64
如有任何想法,我们将不胜感激
您需要 groupby
'A' 列,然后 select 'B' 列并在该列上调用 max()
:
In [42]:
df.groupby('A')['B'].max()
Out[42]:
A
10 1002
20 2003
30 3001
Name: B, dtype: int64
您可以一次对不同的列执行多项功能,请参阅文档:http://pandas.pydata.org/pandas-docs/stable/groupby.html#aggregation
我尝试为每个 A 获得最大的 B。 C 和 D 在那里,因为我的数据集不仅仅是我想要排序并获得最大值的 2 列。
import pandas
import numpy
df = pandas.DataFrame({'A': [10, 10, 20, 20, 30, 20, 10, 20],
'B': [1001, 1002, 2002, 2003, 3001, 2003, 1002, 2003],
'C': numpy.random.randn(8),
'D': numpy.random.randn(8)})
像这样:
df[['A', 'B']].somepandas(magic)
期望的结果是:
B
A
10 1002
20 2003
30 3001
但到目前为止我只知道在不分组的情况下获取每列的最大值:
df[['A', 'B']].max(axis=0)
A 30
B 3001
dtype: int64
如有任何想法,我们将不胜感激
您需要 groupby
'A' 列,然后 select 'B' 列并在该列上调用 max()
:
In [42]:
df.groupby('A')['B'].max()
Out[42]:
A
10 1002
20 2003
30 3001
Name: B, dtype: int64
您可以一次对不同的列执行多项功能,请参阅文档:http://pandas.pydata.org/pandas-docs/stable/groupby.html#aggregation