【问题标题】:Pandas Dataframe - Using Comparison Operator (==) vs idxmin() is producing different resultsPandas Dataframe - 使用比较运算符(==)与 idxmin()产生不同的结果
【发布时间】:2020-08-31 07:15:27
【问题描述】:

这与试图回答的问题之一有关。编号:61801654

数据集:

Q   GDP
2008q3  14891.6 
2008q4  14577.0 
2009q1  14375.0 
2009q2  14355.6

我们的想法是用 Q 的值作为 GDP 的最小值。 正确答案是:

df.loc[df['GDP'].idxmin()]['Q']

输出:

2009q2
<class 'str'>

我认为也可能是这样的答案:

df.loc[df['GDP'] == df['GDP'].min()]['Q']

但是,这个输出是:

3    2009q2
<class 'pandas.core.series.Series'>

作为参考,3 是我使用 read_clipboard(sep='\s\s+') 函数创建的数据帧的索引:

df = pd.read_clipboard(sep='\s\s+')

        Q      GDP
0  2008q3  14891.6
1  2008q4  14577.0
2  2009q1  14375.0
3  2009q2  14355.6

我想了解为什么df.loc[df['GDP'] == df['GDP'].min()]['Q'] 返回一个系列,而df.loc[df['GDP'].idxmin()]['Q'] 只是返回一个字符串值。

找不到已回答的类似问题。如有重复,我深表歉意。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    场景 1

    df['GDP'] == df['GDP'].min() 给你一个布尔系列。

    >>> mask = df['GDP'] == df['GDP'].min()
    >>> mask
    0    False
    1    False
    2    False
    3     True
    Name: GDP, dtype: bool
    

    使用布尔系列 (with or without the loc accessor) 对数据框进行索引会为您提供数据框。

    >>> df_filtered = df.loc[mask]
    >>> type(result1)
    <class 'pandas.core.frame.DataFrame'>
    >>> df_filtered
            Q      GDP
    3  2009q2  14355.6
    

    从数据框中选择一列会给你一个系列。

    >>> type(df_filtered['Q'])
    <class 'pandas.core.series.Series'>
    >>> df_filtered['Q']
    3    2009q2
    Name: Q, dtype: object
    

    场景 2

    df['GDP'].idxmin() 给你一个单一的值。

    >>> idxmin = df['GDP'].idxmin()
    >>> idxmin
    3
    

    选择数据框的单行会返回一个系列。

    >>> row = df.loc[idxmin]
    >>> type(row)
    <class 'pandas.core.series.Series'>
    >>> row
    Q       2009q2
    GDP    14355.6
    Name: 3, dtype: object
    

    对系列进行索引会为您提供单个值(如果索引是唯一的)。

    >>> row['Q']
    '2009q2'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-06
      • 1970-01-01
      • 2020-01-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 2021-11-07
      • 2022-07-19
      相关资源
      最近更新 更多