Numeric types to Aggregate error

Asked

Viewed 197 times

-2

I’m making a program based on a file .csv, but when I run the program the error occurs No numeric types to aggregate.

File part:

datatime,app version,gender,money

02/09/2019,4,F,$7.43

07/25/2019,1,F,$14.66

01/01/2019,4,M,,$9.99

01/30/2019,5,M,$5.61

04/01/2019,4,F,$13.70

09/26/2019,5,M,$8.84

My code:

import pandas as pd

import matplotlib.pyplot as plt

dados = pd.read_csv('./aplicativo.csv', sep = ',', parse_dates = ['datatime'])

dados['mes'] = pd.DatetimeIndex(dados['datatime'], yearfirst = True).month

def media(m):

return pd.DataFrame(m.groupby('mes')['money'].mean()).reset_index()
ind = media(dados)

plt.title('titulo')

plt.plot(ind['mes'], ind['money'], color = 'b')

plt.xlabel('mes')

plt.ylabel('media de valor pago')

plt.show()

1 answer

1

Your error occurs because you are trying to aggregate a string as if it were a numeric variable.

You must turn the money column into numerical value:

dados['money'] = dados['money'].str.replace('$','')
dados['money'] = pd.to_numeric(dados['money'], errors='coerce')

Code:

import pandas as pd 
import matplotlib.pyplot as plt

dados = pd.read_csv('./aplicativo.csv', sep = ',', parse_dates = ['datatime']) 
dados['mes'] = pd.DatetimeIndex(dados['datatime'], yearfirst = True).month

dados['money'] = dados['money'].str.replace('$','')
dados['money'] = pd.to_numeric(dados['money'], errors='coerce')

def media(m):
    return pd.DataFrame(m.groupby('mes')['money'].mean()).reset_index()

ind = media(dados)

plt.title('titulo') 
plt.plot(ind['mes'], ind['money'], color = 'b') 
plt.xlabel('mes') 
plt.ylabel('media de valor pago') 
plt.show() 
  • 1

    Beautiful answer! Adding: the errors='coerce' will put Nan for those values that cannot be converted. Another possibility after removing the $ would be dados['money'] = dados['money'].astype(float, errors='ignore'). Putting errors='ignore' would cause the value, in the case of a conversion error, to be the original. That is, in the case of a conversion error, it would not aggregate.

  • Show Paulo, thanks for the comment! Big hug!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.