优客文库提供全面的范文格式和文档模板,包括申请书、合同、借据、证明、求职信等,助力您快速撰写专业文档。

python使用pycharm引入“北京二手房数据.xlsx”完成数据的预处理:1、提取字符串中的数值信息及统一信息格式2、查找表格中的重复值并处理3、将表格中的面积与总价进行连续数据的离散化4、对城

来自 江苏省南京市 的网友 时间: 热度:°C 加入收藏 我要投稿 点赞()
首先,我们需要安装并导入所需的库,如pandas、numpy、matplotlib和openpyxl。然后按照要求完成数据预处理和可视化。

1. 数据预处理:

```python
import pandas as pd
import numpy as np
import re

# 读取数据
data = pd.read_excel("北京二手房数据.xlsx")

# 提取字符串中的数值信息及统一信息格式
def extract_number(s):
return float(re.findall(r"\d+\.?\d*", s)[0])

data["面积"] = data["面积"].apply(extract_number)
data["总价"] = data["总价"].apply(extract_number)

# 查找表格中的重复值并处理
data = data.drop_duplicates()

# 将表格中的面积与总价进行连续数据的离散化
bins = [0, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000]
data["面积分箱"] = pd.cut(data["面积"], bins=bins)
data["总价分箱"] = pd.cut(data["总价"], bins=bins)

# 对城区、朝向、区域、优点进行字符数据编码
data["城区编码"] = data["城区"].astype("category").cat.codes
data["朝向编码"] = data["朝向"].astype("category").cat.codes
data["区域编码"] = data["区域"].astype("category").cat.codes
data["优点"] = data["优点"].fillna("其他")
data["优点编码"] = data["优点"].astype("category").cat.codes

# 生成“北京二手房数据预处理.xlsx”
data.to_excel("北京二手房数据预处理.xlsx", index=False)
```

2. 数据可视化:

```python
import matplotlib.pyplot as plt

# 导入“北京二手房数据预处理.xlsx”
preprocessed_data = pd.read_excel("北京二手房数据预处理.xlsx")

# 使用柱状图完成各城区的平均单价分布情况
average_price_per_area = preprocessed_data.groupby("城区")["总价"].mean().sort_values()
plt.bar(average_price_per_area.index, average_price_per_area.values)
plt.xlabel("城区")
plt.ylabel("平均单价")
plt.title("各城区的平均单价分布情况")
plt.show()

# 使用散点图完成绘制单价与面积的关系
plt.scatter(preprocessed_data["面积"], preprocessed_data["总价"])
plt.xlabel("面积")
plt.ylabel("总价")
plt.title("单价与面积的关系")
plt.show()

# 使用饼状图完成二手房总价区间
total_price_range = ["0-50万", "50-100万", "100-150万", "150-200万", "200-250万", "250-300万", "300-350万", "350-400万", "400-450万", "450-500万", "500-550万", "550-600万", "600-650万", "650-700万", "700-750万", "750-800万", "800-850万", "850-900万", "900-950万", "950-1000万"]
counts = [len(preprocessed_data[(preprocessed_data["总价"] >= i * 50) & (preprocessed_data["总价"] < (i + 1) * 50)]) for i in range(21)]
plt.pie(counts, labels=total_price_range, autopct="%1.1f%%")
plt.title("二手房总价区间")
plt.show()
```
221381
领取福利

微信扫码领取福利

微信扫码分享