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
使用Python的NumPyPandas和Matplotlib这三个库来进行数据分析项目通常涉及以下几个步骤: 1. **导入库**: - `import numpy as np`: 对于数值计算和数组操作。 - `import pandas as pd`: 主要用于数据加载、清洗和处理。 - `import matplotlib.pyplot as plt`: 用于数据可视化。 2. **数据加载**: - 可能使用`pd.read_csv()`从CSV文件加载数据,或者`pd.read_excel()`加载Excel文件。 ```python data = pd.read_csv('your_data.csv') ``` 3. **数据探索**: - `data.head()`: 查看前几行数据。 - `data.describe()`: 提供统计数据概览。 4. **数据清洗**: - 删除缺失值:`data.dropna()` 或者填充缺失值:`data.fillna(value)`. - 数据转换:如将类别变量编码成数字 (`pd.get_dummies()`)。 5. **数据预处理**: - 特征工程:选择特征、标准化或归一化数值。 6. **数据分析**: - 利用NumPy进行数学运算或创建新的特征。 - 对于分类问题,可能会用到交叉验证 (`sklearn.model_selection.cross_val_score()`)。 7. **绘制图表**: - `plt.plot(data['column_name'])`: 绘制折线图展示趋势。 - `plt.hist(data['column_name'], bins=10)`: 绘制直方图查看分布。 8. **结果呈现**: - 结合matplotlib创建更复杂的可视化,例如箱线图、散点图等。 9. **模型应用**: - 如果需要,可以使用Pandas DataFrame作为训练数据输入机器学习模型。 一个简单的示例项目可能包括分析销售数据,找出销售额随时间的变化趋势,以及最受欢迎的产品类别: ```python # 假设我们有如下数据结构 sales_df = pd.read_csv('sales_data.csv') # 数据清洗 sales_df = sales_df.dropna(subset=['date', 'product']) # 计算月度销售额总和 monthly_sales = sales_df.groupby(sales_df['date'].dt.to_period('M')).sum()['revenue'] # 绘制月度销售额曲线 plt.figure(figsize=(12,6)) plt.plot(monthly_sales) plt.title('Monthly Sales') plt.xlabel('Month') plt.ylabel('Revenue') plt.show() # 分析最畅销产品 top_products = sales_df.groupby('product')['quantity_sold'].sum().sort_values(ascending=False).head(10) # 绘制饼状图展示销量分布 plt.figure() plt.pie(top_products.values, labels=top_products.index, autopct='%1.1f%%') plt.title('Top Products by Sales') plt.show() ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值