0
def answer_six():
    census_df = pd.read_csv('census.csv')
    copy = census_df.copy()
    
    states = copy['STNAME'].unique()
    counties = copy['CTYNAME']
      
    play = copy.copy()

    play = play.set_index(['STNAME','CTYNAME'])
    copy = copy.set_index(['STNAME'])

    def population_with_top3 (state):        
        counties = copy.loc[state]['CTYNAME'].values        
        population_array = list(map(lambda county:int(play.loc[state,county]['CENSUS2010POP'].values),counties))        
        population_array.sort(reverse = True)        
        population = population_array[1] + population_array[2] + population_array[3]            
        return {'STNAME': state, 'POP': population}

    states_with_pop = list(map(population_with_top3,states))              
    return states_with_pop

answer_six()

when running the code I get:

TypeError: only length-1 arrays can be converted to Python scalars

Does anybody have any experience with this kind of issue?

Thanks!

DYZ
  • 55,249
  • 10
  • 64
  • 93
jhzv
  • 28
  • 2
  • 1
    Please include the full error message. – DYZ Aug 21 '20 at 03:46
  • @jhzv `play.loc[state,county]['CENSUS2010POP'].values` is it a single number? then only `int()` works – Girish Hegde Aug 21 '20 at 04:09
  • Does this answer your question? [Python Error only length-1 arrays can be converted to Python scalars](https://stackoverflow.com/questions/43945729/python-error-only-length-1-arrays-can-be-converted-to-python-scalars) – Rohit Aug 21 '20 at 06:47

1 Answers1

0

This error happens when you try to use an array in place of single value. I think the error is in this part of your code.

int(play.loc[state,county]['CENSUS2010POP'].values)

int takes only a single value for typecasting and .values returns an array. But if the array is of size one int will ignore that its an array and take the 1st element. In you case i think your play.loc[,][''].values is returning more than one value. This happens if there is more than one row with same state name, same county name and same CENSUS2010POP.