1

This is related to one of the questions that was trying to respond to. Id: 61801654

Dataset:

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

The idea was to get the value of Q for minm value of GDP. The correct answer was:

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

Output:

2009q2
<class 'str'>

What I thought could also be the answer is this:

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

However, the output with this is:

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

For reference, 3 is the index of the dataframe that I created using the read_clipboard(sep='\s\s+') function:

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

I want to understand why is df.loc[df['GDP'] == df['GDP'].min()]['Q'] returning a series while df.loc[df['GDP'].idxmin()]['Q'] is just returning a string value.

Could not find a similar problem already been answered. My apologies if its a duplicate.

Anshul
  • 1,413
  • 2
  • 6
  • 14

1 Answers1

1

Scenario 1

df['GDP'] == df['GDP'].min() gives you a boolean series.

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

Indexing into a dataframe with a boolean series (with or without the loc accessor) gives you a dataframe.

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

Selecting a column from a dataframe gives you a series.

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

Scenario 2

df['GDP'].idxmin() gives you a single value.

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

Selecting a single row of a dataframe returns a series.

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

Indexing into a series gives you a single value (if the index is unique).

>>> row['Q']
'2009q2'
timgeb
  • 76,762
  • 20
  • 123
  • 145