stackoverflowuser2010
stackoverflowuser2010

Reputation: 41029

Plot Pandas groupby dataframe

I am having some problems with plotting a Pandas dataframe that was created from a groupby() and now has a RangeIndex.

For example, here is my input data with four columns:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
df.head()
#     A   B   C   D
# 0  83  99  55  83
# 1  91  42  14  27
# 2  44   4  30   9
# 3  96  46  92  73
# 4  91  73  17  36

I then apply a groupby() to get two columns: A and the mean of B.

gb = df.groupby(pd.cut(df.A, 10)).B.mean()
gb
# A
# (-0.099, 9.9]    38.272727
# (9.9, 19.8]      49.800000
# (19.8, 29.7]     55.000000
# (29.7, 39.6]     50.454545
# (39.6, 49.5]     46.285714
# (49.5, 59.4]     44.800000
# (59.4, 69.3]     48.500000
# (69.3, 79.2]     55.615385
# (79.2, 89.1]     45.500000
# (89.1, 99]       51.866667
# Name: B, dtype: float64

gb_df = gb.to_frame().reset_index()
gb_df
#                A          B
# 0  (-0.099, 9.9]  38.272727
# 1    (9.9, 19.8]  49.800000
# 2   (19.8, 29.7]  55.000000
# 3   (29.7, 39.6]  50.454545
# 4   (39.6, 49.5]  46.285714
# 5   (49.5, 59.4]  44.800000
# 6   (59.4, 69.3]  48.500000
# 7   (69.3, 79.2]  55.615385
# 8   (79.2, 89.1]  45.500000
# 9     (89.1, 99]  51.866667

Now, when I try to plot A and B, I get an error because column A is of RangeIndex.

plt.scatter(x=gb_df.A, y=gb_df.B)

# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# ValueError: could not convert string to float: (89.1, 99]

Ideally, I would like to plot the lower bound of the A column's RangeIndex as the X-axis. So data like this would be great:

#         A          B
# 0  -0.099  38.272727
# 1     9.9  49.800000
# 2    19.8  55.000000

Thanks for any help.

Upvotes: 2

Views: 655

Answers (1)

BENY
BENY

Reputation: 323386

By using left to get the leftbreak.

gb_df['New_A']=gb_df.A.apply(lambda x : x.left).astype('float')
gb_df.plot.scatter(x = 'New_A', y='B')

enter image description here

Data Info:

gb_df
               A          B   New_A
0  (-0.099, 9.9]  39.928571  -0.099
1    (9.9, 19.8]  33.090909   9.900
2   (19.8, 29.7]  41.900000  19.800
3   (29.7, 39.6]  46.500000  29.700
4   (39.6, 49.5]  52.454545  39.600
5   (49.5, 59.4]  37.866667  49.500
6   (59.4, 69.3]  60.600000  59.400
7   (69.3, 79.2]  71.300000  69.300
8   (79.2, 89.1]  42.714286  79.200
9   (89.1, 99.0]  52.545455  89.100

Upvotes: 1

Related Questions