1

I need to convert a data frame query into a dictionary variable but it is saving the STATE and Occurrences as one variable. I need them separate so I can plot a bar chart from it Am I doing it wrong?

Code for dataframe to dict

df = pd.DataFrame(data_dict)
df = df['xyz'].value_counts().to_frame()
df.to_dict('dict')
print (dict)

Code i want to use to plot my bar chart

data = (dict)
names = list(data.keys())
values = list(data.values())
plt.bar(range(len(data)),values,tick_label=names)
plt.show()
NinJesus
  • 17
  • 5
  • Possible duplicate of [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – NinJesus Apr 12 '19 at 03:26

1 Answers1

0

In my opinion convert back to dictionary is not necessary, use Series.plot.bar instead:

df = pd.DataFrame(data_dict)
s = df['STATE'].value_counts()

s.plot.bar()

Solution with pyplot.bar:

plt.bar(range(len(s)),s,tick_label=s.index)

EDIT: You are realy close, only remove to_frame for convert Series to dict:

df = pd.DataFrame(data_dict)
s = df['STATE'].value_counts()

data = s.to_dict()
names = list(data.keys())
values = list(data.values())
plt.bar(range(len(data)),values,tick_label=names)
plt.show()

If want use one column DataFrame add STATE before convert to dict:

df = df['STATE'].value_counts().to_frame()

#select column `STATE`
data = df['STATE'].to_dict('dict')

names = list(data.keys())
values = list(data.values())
plt.bar(range(len(data)),values,tick_label=names)
plt.show()
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252