gpt4 book ai didi

python - 按数据框绘制 Pandas group

转载 作者:太空宇宙 更新时间:2023-11-04 04:54:56 24 4
gpt4 key购买 nike

我在绘制从 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com