Jump to content

Novato


Recommended Posts

Amigos, boa tarde!

Estou iniciando na programação Python. E estou encontrando este erro:

not_found = list(ensure_index(key)[missing_mask.nonzero()[0]].unique())

KeyError: "None of [Index(['1990', '1991', '1992', '1993', '1994', '1995', '1996', '1997', '1998',\n
'1999', '2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007',\n
'2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016',\n
'2017', '2018', '2019', '2020', '2021'],\n
dtype='object')] are in the [columns]"

Meu dataframe df_tot

image.png

Ao tentar executar este código para gerar um gráfico de regressão

#YEARS which we will use for plotting later
years = list(map(str, range(1990, 2022)))

#Using the sum() method to get the total fuel per year
df_tot = pd.DataFrame(df_comb[years].sum(axis=0))
df_tot.head()

#change the years to type float (useful for regression later on)
df_tot.index = map(float, df_tot.index)

#reset the index to put in back in as a column in the df_tot dataframe
df_tot.reset_index(inplace=True)

#rename columns
df_tot.columns = ['year', 'TOTAL']

#view the final dataframe
df_tot.head()

Obrigado!

Link to comment
Share on other sites

  • Pessoal da TecnoSpeed

Olá @ENSS tudo bem?

Vamos lá para entender o que aconteceu.


Poderia me explicar brevemente o objetivo desta parte aqui

not_found = list(ensure_index(key)[missing_mask.nonzero()[0]].unique())

O erro está acontecendo em qual linha exatamente... nesta acima ?

Pelo que estou vendo ele não esta conseguindo encontrar aqueles valores ali como colunas... Verifica os nomes das colunas se esta como texto mesmo, recomendo analisar novamente esse processo, as vezes algo passou despercebido....

Infelizmente não consigo lhe dar uma resposta mais assertiva com as informações que estou vendo, talvez seja erro meu, mas se possível poderia explicar mais detalhadamente o que está tentando fazer no DataFrame que resultou neste erro, a partir dai acredito que conseguirei lhe ajudar de forma mais assertiva. 

Link to comment
Share on other sites

Thanael, obrigado por responder o post.

Mas consegui descobrir.

Eu gerei uma list com os anos de 1990 - 2021. O fato, não sei porque o dataframe não carregava os anos 1992 a 2002. 

No inicio eu estava gerando esta condição

gasolina_df=gasolina_df.loc[gasolina_df['MUNICÍPIO']=='VOLTA REDONDA']

após mudar o filtro para

gasolina_df=gasolina_df.loc[gasolina_df['CÓDIGO IBGE']==3306305]

Consegui carregar todos os dados para o dataframe.

Agora, eu gostaria que o total mostrado no gráfico Waffle (GASOLINA / ETANO/DIESEL) fossem em porcentagem.. Poderia ajudar.

#instantiate a new figure object
fig = plt.figure()

#use matshow to display the waffle chart
colormap = plt.cm.coolwarm
plt.matshow(waffle_chart, cmap=colormap)
plt.colorbar()

#get the axis
ax=plt.gca()

#set minor ticks
ax.set_xticks(np.arange(-.5, (width), 1), minor=True)
ax.set_yticks(np.arange(-.5, (height), 1), minor=True)

#add gridlines based on minor ticks
ax.grid(which='minor', color='w', linestyle='-', linewidth=2)

plt.xticks([])
plt.yticks([])

#compute cumulative sum of individual categories to match color schemes between chart and legend
values_cumsum = np.cumsum(tged_df['TOTAL'])
total_values = values_cumsum[len(values_cumsum) - 1]

#Create legend
legend_handles = []
for i, category in enumerate (tged_df.index.values):
    label_str = category + '(' + str(tged_df['TOTAL'][i]) + ')'
    color_val = colormap(float(values_cumsum[i])/total_values)
    legend_handles.append(mpatches.Patch(color=color_val, label=label_str))

    
#Add legend to chart
plt.legend(handles=legend_handles,
          loc='lower center',
          ncol = len(tged_df.index.values),
          bbox_to_anchor=(0., -0.2, 0.95, .1)
          )
plt.show()

 

image.png

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


×
×
  • Create New...