数据处理模块(numpy,panads)-案例

数据处理(panads与numpy)模块

#读取数据
import pandas as pd
import numpy as np
file_path = open('地址')
file_date = pd.read_csv(file_path)
file_date.head()##tail()

#数据预处理
file_date.duplicated()#重复值检测
file_date = file_date.drop_duplicates()#删除重复值
file_date = file_date.dropna()#删除缺失值
date_new = np.array([])#创建空数组
date = file_date['列名'].values#处理一列数据
for i in date:
    date_new = np.append(date_new,np.array(i[:-2]))
date = date_new.astype(np.float64)#转换数据类型
file_date.loc[:,'列名'] = date
file_date

housetype_data = file_date['户型']
temp_list = []
#replace方法替换
for i in housetype_data:
    new info = i.replace('房间','室')
    temp_list.append(new_info)
file_date.loc[:,'户型'] = temp_list
file_date
####图表分析
#按区域列分组file_date,并统计每个分组的量
new_df = pd.DataFrame({'区域':file_date['区域'].unique(),'数量':[0]*13})
new_df
new_df.sort_values(by=['数量'],ascending=False)#按数量从小到大排列
file_date['位置'] = '北京市'+file_date['区域'].values+'区'+file_date['小区名称'].values
file_date#增加一列
##获取经纬度
##
##户型数量分析
#定义函数,用于计算各户型数量
def all_house(arr):
    arr = np.array(arr)
    key = np.unique(arr)
    result = {}
    for k in key:
        mask = (arr == k)
        arr_new = arr[mask]
        v = arr_new.size
        result[k] = v
    return result
#获取户型数据
house_array = file_date['户型']
house_info = all_house(house_array)
house_info

#使用字典推导式
house_type = dict((key,value for key, value) in house_info.items() if value > 50)
show_houses = pd.DataFrame({'户型':[x for x inm house_type.values()]})
show_houses

##可视化
import matplotlib.pyplt as plt
import matplotlib
%matplotlib inline
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False
house_type = show_houses['数量']
plt.barh(range(11),house_type_num,height=0.7,color='steelblue',alpha=0.8)
plt.yticks(range(11),house_type)
plt.xlim(0,2500)
plt.xlabel('数量')
plt.ylabel('户型种类')
plt.title('北京地区各户型房屋数量')
for x,y in enumerate(house_type_num):
    plt.text(y + 0.2,x - 0.1,'%s' % y)
plt.show()

##平均租金分析
#建对象 初始化房租总金额 总面积为0
df_all = pd.DataFrame({'区域':file_date['区域'].unique(),
                      '房租总金额':[0]*13,'总面积':[0]*13})
df_all

#求总金额和总面积
sum_price = file_date['价格(元/月)']。groupby(file_date['区域']).sum
sun_area = file_date['面积(㎡)']。groupby(file_date['区域']).sum
df_all['房租总金额'] = sum_price.values
df_all['总面积(㎡)'] = sum_area.values
df_all

#计算各区域平方米房租价格,并保留两位小数
df_all['每平米租金(元)'] = round(df_all['房租总金额']/df_all['总面积(㎡)'],2)
df_all

#合并new_df df_all
df_merge = pd.merge(new_df,df_all)
df_merge

##折线图
import matplotlib.ticker as mtick
from matplotlib.font_manager import FontProperties
num = df_merge['数量']
price=dgf_merge['每平米租金(元)']
l=[i for i inrange(11)]
plt.rcParams['font.sans-serif']=['SimHei']
lx=df_merge['区域']
fig = plt.figure()
axl = fig,add_subplot(111)
ax1.plot(1,price,'or-',label='价格')
for i,(_x,_y) in enumerate(zip(l,price)):
    plt.text(_x,_y,price[i],color='black',fontsize=10)
axl.set_ylim([0,200])
axl.set_ylabel('价格')
plt.legend(prop={'family':'SimHei','size':8},loc='upper left')
ax2 = axl.twinx()
plt.bar(l,num,alpha=0.3,color='green',label='数量')
ax2.set_ylabel('数量')
ax2.set_ylim([0,2000])
plt.legend(prop={'family':'SimHei','size':8},loc='upper right')
plt.xticks(l,lx)
plt.show()


#面积区间分析
# 查看房屋的最大面积和最小面积
print('房屋最大面积是%d平米'%(file_data['面积(㎡)'].max()))
print('房屋最小面积是%d平米'%(file_data['面积(㎡)'].min()))
# 查看房租的最高值和最小值
print('房租最高价格为每月%d元'%(file_data['价格(元/月)'].max()))
print('房屋最低价格为每月%d元'%(file_data['价格(元/月)'].min()))


# 面积划分
area_divide = [1, 30, 50, 70, 90, 120, 140, 160, 1200]
area_cut = pd.cut(list(file_data['面积(㎡)']), area_divide)
area_cut_data = area_cut.describe()
area_cut_data

##扇形图
import numpy as np
area_percentage = (area_cut_data['freqs'].values)*100
# 保留两位小数
np.set_printoptions(precision=2)
labels  = ['30平米以下', '30-50平米', '50-70平米', '70-90平米',
'90-120平米','120-140平米','140-160平米','160平米以上']
plt.axes(aspect=1)
plt.pie(x=area_percentage, labels=labels, autopct='%.2f %%',
           shadow=True, labeldistance=1.2, startangle = 90,pctdistance = 0.7)
plt.legend(loc='upper right')
plt.show()

自己想要操作的可以私信我 我发文件 这个上传文件到百度网盘太难了

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值