通过数据帧

时间:2017-11-14 23:07:18

标签: 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

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

使用left来获取左翼。

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