Umang Mistry
Umang Mistry

Reputation: 363

ValueError: Must pass DataFrame with boolean values only

Question

In this datafile, the United States is broken up into four regions using the "REGION" column.

Create a query that finds the counties that belong to regions 1 or 2, whose name starts with 'Washington', and whose POPESTIMATE2015 was greater than their POPESTIMATE 2014.

This function should return a 5x2 DataFrame with the columns = ['STNAME', 'CTYNAME'] and the same index ID as the census_df (sorted ascending by index).

CODE

    def answer_eight():
    counties=census_df[census_df['SUMLEV']==50]
    regions = counties[(counties[counties['REGION']==1]) | (counties[counties['REGION']==2])]
    washingtons = regions[regions[regions['COUNTY']].str.startswith("Washington")]
    grew = washingtons[washingtons[washingtons['POPESTIMATE2015']]>washingtons[washingtons['POPESTIMATES2014']]]
    return grew[grew['STNAME'],grew['COUNTY']]

outcome = answer_eight()
assert outcome.shape == (5,2)
assert list (outcome.columns)== ['STNAME','CTYNAME']
print(tabulate(outcome, headers=["index"]+list(outcome.columns),tablefmt="orgtbl"))

ERROR

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-77-546e58ae1c85> in <module>()
      6     return grew[grew['STNAME'],grew['COUNTY']]
      7 
----> 8 outcome = answer_eight()
      9 assert outcome.shape == (5,2)
     10 assert list (outcome.columns)== ['STNAME','CTYNAME']

<ipython-input-77-546e58ae1c85> in answer_eight()
      1 def answer_eight():
      2     counties=census_df[census_df['SUMLEV']==50]
----> 3     regions = counties[(counties[counties['REGION']==1]) | (counties[counties['REGION']==2])]
      4     washingtons = regions[regions[regions['COUNTY']].str.startswith("Washington")]
      5     grew = washingtons[washingtons[washingtons['POPESTIMATE2015']]>washingtons[washingtons['POPESTIMATES2014']]]

/opt/conda/lib/python3.5/site-packages/pandas/core/frame.py in __getitem__(self, key)
   1991             return self._getitem_array(key)
   1992         elif isinstance(key, DataFrame):
-> 1993             return self._getitem_frame(key)
   1994         elif is_mi_columns:
   1995             return self._getitem_multilevel(key)

/opt/conda/lib/python3.5/site-packages/pandas/core/frame.py in _getitem_frame(self, key)
   2066     def _getitem_frame(self, key):
   2067         if key.values.size and not com.is_bool_dtype(key.values):
-> 2068             raise ValueError('Must pass DataFrame with boolean values only')
   2069         return self.where(key)
   2070 

ValueError: Must pass DataFrame with boolean values only

I am clueless. Where am I going wrong?

Thanks

Upvotes: 8

Views: 29755

Answers (6)

Melwin Varghese
Melwin Varghese

Reputation: 3

I solved it in this way (I have not used any Local variables directly accessed census_df in a single line) Solution is the Pretty much the same as you see the other solutions, but in the other solutions, they have used the local variables in my solutions I have not used it.

def answer_eight(): 
    return census_df[
          (census_df['SUMLEV'] == 50)                                     &
          ((census_df["REGION"] == 1) | (census_df["REGION"] == 2))       &
          (census_df["CTYNAME"].str.lower()).str.startswith('washington') &
          (census_df["POPESTIMATE2015"] > census_df["POPESTIMATE2014"])        
         ][["STNAME","CTYNAME"]]

Upvotes: 0

CabantingDave
CabantingDave

Reputation: 11

I solved the problem at Coursera like this.

def answer_eight():
    df8 = census_df.copy()
    washington = df8['CTYNAME'].str[0:10] == 'Washington'
    popincrease = df8['POPESTIMATE2015']) > (df8['POPESTIMATE2014']
    region = (df8['REGION'] == 1) | (df8['REGION'] == 2)
    
df8 = df8[region & popincrease & washington]

    return df8[{'STNAME','CTYNAME'}]

answer_eight()

I was a beginner in Pandas back then and it took me almost 20 LOLs.

Upvotes: 0

Jay Mulani
Jay Mulani

Reputation: 1

def answer_eight():
    df=census_df
    region1=df[ df['REGION']==1 ]
    region2=df[ df['REGION']==2 ]

    yes_1=region1[ region1['POPESTIMATE2015'] > region1['POPESTIMATE2014']]
    yes_2=region2[ region2['POPESTIMATE2015'] > region2['POPESTIMATE2014']]

    yes_1=yes_1[ yes_1['CTYNAME']=='Washington County' ]
    yes_2=yes_2[ yes_2['CTYNAME']=='Washington County' ]

    ans=yes_1[ ['STNAME','CTYNAME'] ]  
    ans=ans.append(yes_2[ ['STNAME','CTYNAME'] ])
    return ans.sort()

Upvotes: 0

yogs
yogs

Reputation: 53


def answer_eight():
    county = census_df[census_df['SUMLEV']==50]
    req_col = ['STNAME','CTYNAME']

    region = county[(county['REGION']<3) & (county['POPESTIMATE2015']>county['POPESTIMATE2014']) & (county['CTYNAME'].str.startswith('Washington'))]
    region = region[req_col]

    return region
answer_eight()

Upvotes: 0

gourav chatterjee
gourav chatterjee

Reputation: 11

def answer_eight():
    df=census_df[census_df['SUMLEV']==50]
    #df=census_df
    df=df[(df['REGION']==1) | (df['REGION']==2)]
    df=df[df['CTYNAME'].str.startswith('Washington')]
    df=df[df['POPESTIMATE2015'] > df['POPESTIMATE2014']]
    df=df[['STNAME','CTYNAME']]
    print(df.shape)
    return df.head(5)

Upvotes: 1

EdChum
EdChum

Reputation: 393933

You're trying to use a different shaped df to mask your df, this is wrong, additionally the way you're passing the conditions is being used incorrectly. When you compare a column or series in a df with a scalar to produce a boolean mask you should pass just the condition, not use this successively.

def answer_eight():
    counties=census_df[census_df['SUMLEV']==50]
    # this is wrong you're passing the df here multiple times
    regions = counties[(counties[counties['REGION']==1]) | (counties[counties['REGION']==2])]
    # here you're doing it again
    washingtons = regions[regions[regions['COUNTY']].str.startswith("Washington")]
    # here you're doing here again also
    grew = washingtons[washingtons[washingtons['POPESTIMATE2015']]>washingtons[washingtons['POPESTIMATES2014']]]
    return grew[grew['STNAME'],grew['COUNTY']]

you want:

def answer_eight():
    counties=census_df[census_df['SUMLEV']==50]
    regions = counties[(counties['REGION']==1]) | (counties['REGION']==2])]
    washingtons = regions[regions['COUNTY'].str.startswith("Washington")]
    grew = washingtons[washingtons['POPESTIMATE2015']>washingtons['POPESTIMATES2014']]
    return grew[['STNAME','COUNTY']]

Upvotes: 6

Related Questions