python - 按数据框绘制 Pandas group

标签 python pandas matplotlib

我在绘制从 groupby() 创建的 Pandas 数据框时遇到了一些问题,现在有一个 RangeIndex。

例如,这是我的四列输入数据:

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

然后我应用 groupby() 来获得两列:A 和 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

现在,当我尝试绘制 A 和 B 时,出现错误,因为 A 列属于 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]

理想情况下,我想将 A 列的 RangeIndex 的下限绘制为 X 轴。所以像这样的数据会很棒:

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

感谢您的帮助。

最佳答案

通过使用 left 来获得 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

数据信息:

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

关于python - 按数据框绘制 Pandas group,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47296752/

相关文章:

python - 在 Python/Numpy/Pandas 中查找连续值 block 的开始和停止

python - 如何防止 celery 执行相同的任务?

python - 将 Pandas 数据框汇总为半小时一次

python - 我在 matplotlib (python) 中有一个带有误差线的条形图,但我想要误差线在中间。我该怎么做呢?谢谢

Python 绘制 for 循环内的 for 循环生成的数据

python - Tensorflow:调整图像占位符大小

python - 这个排序算法的名称是什么?是冒泡排序吗?最简单的排序?

python - Pandas :从列列表中替换值列表

python - 基于分组列的条件总和

python - 在 Jupyter iPython Notebook 中使用 matplotlib 绘制图形