1

I'm trying to sum an entire column by country, but when I use

my_df.groupby('COUNTRY').VALUES.mean()

It throws a

DataError: No numeric types to aggregate

And when I use

my_df.groupby('COUNTRY').VALUES.sum()

It produces really big values that are far from realistic (maybe by adding them as strings together?)

Could it be that it interprets the values in the column as strings, or am I using the function the wrong way?

I'm trying to accomplish exactly what this guy is doing at 1:45 https://www.youtube.com/watch?v=qy0fDqoMJx8

i.e the values column contains integers that I want to sum by each country.

zagzig
  • 69
  • 1
  • 5
  • `i.e the values column contains integers that I want to sum by each country.` Are you sure? Can you prove it by `print(my_df.dtypes)` ? – jpp Jul 06 '18 at 10:29
  • I meant integer as in a whole number, not a data type, I should have made that clear – zagzig Jul 06 '18 at 11:26

3 Answers3

0

The values in the column was interpreted as strings, they explain how to convert the datatype in this question

Change data type of columns in Pandas

zagzig
  • 69
  • 1
  • 5
0

I understand you are trying to achieve a count of countries, but Is not clear if you want the count the countries or it is based on another variable: Try: my_df['COUNTRY'].value_counts() within the same column or if the sum is based on another variable: my_df[['COUNTRY','other_variable']].groupby(['COUNTRY']).sum()

Your question is not clear, you should show your dataframe

VMEscoli
  • 1,192
  • 1
  • 10
  • 20
  • I meant the sum of all values that are found in columns that have a certain 'COUNTRY' string value. – zagzig Jul 06 '18 at 11:27
0

You need to convert your VALUES series to a numeric type before performing any computations. For example, for conversion to integers:

# convert to integers, non-convertible values will become NaN
my_df['VALUES'] = pd.to_numeric(my_df['VALUES'], downcast='integer', errors='coerce')

# perform groupby as normal
grouped = my_df.groupby('COUNTRY')['VALUES'].mean()
jpp
  • 159,742
  • 34
  • 281
  • 339