3

I have a dataframe I usesd groupby to get the table below

    time_groups=time_data.groupby('time_binned').mean()
    time_groups

**enter image description here**

Then I try to build a bar chart to show the 'Status' column result, but I got error TypeError: unsupported operand type(s) for -: 'str' and 'float'

plt.bar(time_groups.index.astype(str),100*time_groups['Status'])
2
  • I think you shouldn't pass strings as the first argument to plt.bar. Instead use something like range(len(time_groups.index)) and adjust the labels later on via plt.xticks. Commented Aug 20, 2018 at 21:47
  • time_groups[['status']].plot.bar()? Commented Aug 20, 2018 at 21:48

2 Answers 2

3

The reason you see the error is because the first argument (x) is required to be numeric. This is because you're specifying the x-coordinates of the plot. Try doing this:

plt.bar(x = np.arange(0, len(time_groups['Status'])), height = time_groups['Status'])
plt.xticks(np.arange(0, len(time_groups['Status'])), time_groups.index.values)
plt.show()
Sign up to request clarification or add additional context in comments.

3 Comments

Hi Vishnu, it shows another error bar() missing 1 required positional argument: 'left'
Quick question Kunchur, what about if I want to use time_binned column data as my xsticks, do you know what will be the good method to do that?
It solved, I used the code you worte above and it works. Thank you very much.
0

I have found the solution. Instead of the single groupby statement, this is how you do it:

Group by 'State' and sum only the numeric columns:

df2 = df.groupby('State')[['Deaths', 'Cases']].sum().reset_index()

If you still want 'County' information (for example, count of unique counties per state), you can add it separately:

df_counties = df.groupby('State')['County'].nunique().reset_index()
df_counties.rename(columns={'County': 'Unique_Counties'}, inplace=True)

Merge the two dataframes to get a single dataframe with all the desired information:

df2 = df2.merge(df_counties, on='State')

2 Comments

What did you use for input data prior to groupby? OP hasn't even shared it ; this was a rather poorly-formulated question to begin with
Also how does your method affect the required subsequent bar plot, which you do not mention?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.