【问题标题】:What's the Python/pandas equivalent to this SQL for finding both the max value and column-name?用于查找最大值和列名的与此 SQL 等效的 Python/pandas 是什么?
【发布时间】:2013-11-14 02:57:49
【问题描述】:

MAX(variable) 语句的 python/pandas 等价物是什么:

SELECT ID, Name FROM Table5 WHERE 
Friend_count = (SELECT MAX(friend_count) FROM Table5);

(我正在尝试学习如何在 Python 中做一些我通常会在 SQL 中做的事情。我认为我可以在 pandas 中做到这一点,但没有找到方法。)

【问题讨论】:

  • 在python中max()的等价物是max()。我真的不确定你还想要什么?澄清问题或查看上面的文档。
  • 离题:根本没有显示研究尝试。
  • 澄清一下:您是否有一个 pandas DataFrame 试图在其中找到 friend_count 列的最大值,或者您正在使用一些本机 Python 数据结构?
  • @DSM 五年过去了,OP 没有说,但由于他们询问使用表格,因此可以合理地假设他们正在使用 pandas DataFrame(/Series)

标签: python sql pandas dataframe max


【解决方案1】:

在您的DataFrame 上使用idxmax() 方法怎么样?

import numpy as np
import pandas as pd
from ggplot import meat

我在这里使用ggplot 中的肉类数据集。

In [18]: meat
Out[18]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 827 entries, 0 to 826
Data columns (total 8 columns):
date               827  non-null values
beef               827  non-null values
veal               827  non-null values
pork               827  non-null values
lamb_and_mutton    827  non-null values
broilers           635  non-null values
other_chicken      143  non-null values
turkey             635  non-null values
dtypes: datetime64[ns](1), float64(7)

假设您要查找beef 产量最高的行。

In [36]: meat.beef.max()
Out[36]: 2512.0

在 SQL 中你可能会这样做

SELECT 
    * 
FROM 
    meat 
WHERE
    beef = (SELECT max(beef) FROM meat) ;

使用 pandas,您可以像这样使用 idxmax 完成此操作:

In [35]: meat.ix[meat.beef.idxmax()]
Out[35]:
date               2002-10-01 00:00:00
beef                              2512
veal                              18.7
pork                              1831
lamb_and_mutton                   19.7
broilers                        2953.3
other_chicken                     50.7
turkey                           525.9
Name: 705, dtype: object

idxmax 非常棒,如果您的数据是基于日期或时间的,它也应该可以工作。

In [42]: ts = meat.set_index(['date'])

In [43]: ts.beef.max()
Out[43]: 2512.0

In [44]: ts.beef.idxmax()
Out[44]: Timestamp('2002-10-01 00:00:00', tz=None)

In [45]: ts.ix[ts.beef.idxmax()]
Out[45]:
beef               2512.0
veal                 18.7
pork               1831.0
lamb_and_mutton      19.7
broilers           2953.3
other_chicken        50.7
turkey              525.9
Name: 2002-10-01 00:00:00, dtype: float64

【讨论】:

  • 在适用时,这很好用,但如果不止一行达到最大值,您可能会遇到麻烦,因为idxmax 只返回第一行。
【解决方案2】:

假设你有一个 Person 类。它有一个属性friend_count。这是一个找到朋友最多的人的示例...

import operator

class Person(object):
    def __init__(self, friend_count):
        self.friend_count = friend_count

people = [Person(x) for x in [0, 1, 5, 10, 3]]
popular_person = max(people, key=operator.attrgetter('friend_count'))
print popular_person.friend_count # prints 10

【讨论】:

    【解决方案3】:

    熊猫系列/专栏中有max method

    In [1]: df = pd.DataFrame([[1, 2], [3, 4]], columns=['A', 'B'])
    
    In [2]: df
    Out[2]: 
       A  B
    0  1  2
    1  3  4
    

    选择列:

    In [3]: s = df.A  # same as df['A']
    

    取最大值:

    In [4]: s.max()
    Out[4]: 3
    

    您也可以拨打max over the DataFrame

    In [5]: df.max() # over the columns
    Out[5]: 
    A    3
    B    4
    dtype: int64
    
    In [6]: df.max(axis=1) # over the rows
    Out[6]: 
    0    2
    1    4
    dtype: int64
    

    要返回所有具有最大值的行,您应该使用掩码:

    In [7]: df.A == df.A.max()
    Out[7]: 
    0    False
    1     True
    Name: A, dtype: bool
    
    In [8]: df[df.A == df.A.max()]
    Out[8]: 
       A  B
    1  3  4
    

    【讨论】:

    • 有没有比df.loc[df.Friend_count == df.Friend_count.max(), ["ID", "Name"]]之类的更好的方法来获取达到最大值的行?
    • @DSM 我认为这是不久前出现的,我认为这样做几乎总是最好的
    【解决方案4】:

    为了从 Python 中的列表中获取最大值,只需使用 max 函数。这同样适用于min。请参阅位于 here 的文档。如果您希望基于对象的属性进行操作,则可以使用 max(person.age for person in people) 之类的列表推导。

    如果你想获得年龄最大的人,那么你可以使用列表推导式

    oldest_age = max(person.age for person in people)
    people_with_max_age = [person for person in people if people.age == oldest_age]
    

    与 SQL 不同,您很少希望只收集对象的 n 个属性 - 将它们附加在对象上并创建所需对象的集合会更有用。如果您想实现这一点,请参阅@FogleBird 的回答。

    【讨论】:

    • 这会给你最大年龄(整数值),但不是具有最大值的人实例。看我的回答。
    • 他的例子只获得了最高的朋友数 - 我的例子正好可以。
    • 他的示例获取了 ID 和名称。
    猜你喜欢
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多