numpy , pandas 划分bins

numpy 中划分bins,并计算一个bin内的均值

import numpy
data = np.array([range(100)])
bins = numpy.linspace(0, 50, 10)
bins=np.append(bins,np.inf)#最后一个bin到无穷大
digitized = numpy.digitize(data, bins)#Return the indices of the bins to which each value in input array belongs.
# 计算bin内均值法一
bin_means = [data[digitized == i].mean() for i in range(1, len(bins))]
#法二
bin_means1 = (numpy.histogram(data, bins, weights=data)[0] /
             numpy.histogram(data, bins)[0])
# https://stackoverflow.com/questions/6163334/binning-data-in-python-with-scipy-numpy

如果numpy.digitize(data, bins)中,data,超过bins的边缘,那么函数会自动在bins边缘加一个bin,如:

data=np.array([-1,0.5,1.5,2.5,3.5,4.5,5,6])
bins=np.linspace(0,5,6)
print(bins)
di=np.digitize(data,bins)
dt=np.c_[data,di]
print(dt)
'''
[0. 1. 2. 3. 4. 5.]
[[-1.   0. ]
 [ 0.5  1. ]
 [ 1.5  2. ]
 [ 2.5  3. ]
 [ 3.5  4. ]
 [ 4.5  5. ]
 [ 5.   6. ]
 [ 6.   6. ]]
 '''

解释下法二,
numpy.histogram(a, bins=10, range=None, normed=None, weights=None, density=None)

  • Returns
    histarray
    The values of the histogram. See density and weights for a description of the possible semantics.
    bin_edges array of dtype float
    Return the bin edges (length(hist)+1).
  • Parameters
    weights array_like, optional
    An array of weights, of the same shape as a. Each value in a only contributes its associated weight towards the bin count (instead of 1).

举例说明这里怎么计算均值,一个bin里包括[1,2,3,4],那么
n u m p y . h i s t o g r a m ( d a t a , b i n s , w e i g h t s = d a t a ) [ 0 ] / n u m p y . h i s t o g r a m ( d a t a , b i n s ) [ 0 ] = ( 1 ∗ 1 + 2 ∗ 1 + 3 ∗ 1 + 4 ∗ 1 ) / 4 = 2.5 numpy.histogram(data, bins, weights=data)[0] /numpy.histogram(data, bins)[0]=(1*1+2*1+3*1+4*1)/4=2.5 numpy.histogram(data,bins,weights=data)[0]/numpy.histogram(data,bins)[0]=(11+21+31+41)/4=2.5

pandas 划分bins

a=pd.DataFrame(np.random.rand(10,1),columns=['A'])
a['A_cat']=pd.cut(a['A'],bins=np.linspace(0,1,5),labels=[1,2,3,4])

显然labels应该比bins多一个。
参考:

  1. Hands-on Machine Learning with Scikit-Learn, Keras, and TensorFlow
  2. https://stackoverflow.com/questions/6163334/binning-data-in-python-with-scipy-numpy
好的,那我们开始吧。 首先,我们需要安装必要的库,包括numpypandas和matplotlib。你可以通过以下命令来安装: ``` pip install numpy pandas matplotlib ``` 接下来,我们需要获取数据。我们可以从58同城的房产页面上爬取数据。这里我们使用Python中的requests库和BeautifulSoup库来实现。 ```python import requests from bs4 import BeautifulSoup url = 'https://cd.58.com/ershoufang/' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'} r = requests.get(url, headers=headers) soup = BeautifulSoup(r.text, 'html.parser') house_list = soup.find_all('div', {'class': 'property_content'}) ``` 现在我们已经成功获取了房屋列表。接下来,我们需要将它们保存到一个数据框中,以便进行分析。 ```python import pandas as pd data = [] for house in house_list: title = house.find('h3').text.strip() info_list = house.find('div', {'class': 'property_des'}).find_all('p') area = info_list[0].text.strip() layout = info_list[1].text.strip() direction = info_list[2].text.strip() floor = info_list[3].text.strip() age = info_list[4].text.strip() price = house.find('div', {'class': 'property_price'}).find('p').text.strip() data.append({'title': title, 'area': area, 'layout': layout, 'direction': direction, 'floor': floor, 'age': age, 'price': price}) df = pd.DataFrame(data) ``` 现在我们已经成功将数据保存到一个数据框中。我们可以开始对数据进行分析了。 首先,我们可以查看数据的基本统计信息。 ```python print(df.describe()) ``` 接下来,我们可以绘制一个房价分布图,以了解房价的分布情况。 ```python import matplotlib.pyplot as plt plt.hist(df['price'], bins=20) plt.xlabel('Price') plt.ylabel('Count') plt.show() ``` 我们还可以绘制一个散点图,以了解房价与面积之间的关系。 ```python plt.scatter(df['area'], df['price']) plt.xlabel('Area') plt.ylabel('Price') plt.show() ``` 最后,我们可以绘制一个箱线图,以了解不同户型的房价分布情况。 ```python import seaborn as sns sns.boxplot(x='layout', y='price', data=df) plt.show() ``` 这样,我们就完成了58同城成都房价的数据分析。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值