新手学习python,目前正忙于一项任务。我正在尝试从熊猫表中的一些数据中发布散点图,但似乎无法解决。
以下是我的数据集示例:
import pandas as pd
data = {'housing_age': [14, 11, 3, 4],
'total_rooms': [25135, 32627, 39320, 37937],
'total_bedrooms': [4819, 6445, 6210, 5471],
'population': [35682, 28566, 16305, 16122]}
df = pd.DataFrame(data)
我正在尝试在housing_age中的数据上绘制散点图,但是很难弄清楚。
最初尝试将x轴作为'housing_data',将y轴作为对房屋数据的计数,但无法使代码正常工作。然后在某处读取x轴应该是可变的,并且y轴应该是恒定的,因此请尝试以下代码:
x='housing_data'
y=[0,5,10,15,20,25,30,35,40,45,50,55]
plt.scatter(x,y)
ax.set_xlabel("Number of buildings")
ax.set_ylabel("Age of buildings")
但是出现此错误: ValueError:x和y的大小必须相同
请注意-“ housing_data”中的数据范围为1-53年。
我想这应该是一件很容易的事,但是由于某种原因我无法弄清楚。
有人有什么秘诀吗?
答案 0 :(得分:0)
我了解您正在开始,所以混乱很普遍。请忍受我。
从您的描述来看,您好像交换了TResponse
和x
:
y
通常,如果您有一个观测值列表,并且希望对多个类别进行计数,则称为直方图。熊猫具有许多方便的功能,可让您快速查看数据。这个问题的重点之一是# x is the categories: 0-5 yrs, 5-10 yrs, ...
x = [0,5,10,15,20,25,30,35,40,45,50,55]
# y is the number of observations in each category
# I just assigned it some random numbers
y = [78, 31, 7, 58, 88, 43, 47, 87, 91, 87, 36, 78]
plt.scatter(x,y)
plt.set_title('Housing Data')
-创建直方图:
hist
您还可以明确设置垃圾箱:0-5、5-10,...,50-55
# A series of 100 random buildings whose age is between 1 and 55 (inclusive)
buildings = pd.Series(np.random.randint(1, 55, 100))
# Make a histogram with 10 bins
buildings.hist(bins=10)
# The edges of those bins were determined automatically so they appear a bit weird:
pd.cut(buildings, bins=10)
0 (22.8, 28.0]
1 (7.2, 12.4]
2 (33.2, 38.4]
3 (38.4, 43.6]
4 (48.8, 54.0]
...
95 (48.8, 54.0]
96 (22.8, 28.0]
97 (12.4, 17.6]
98 (43.6, 48.8]
99 (1.948, 7.2]