1、随机生成100*5的数值矩阵,每一行代表一个样本,每个样本采集5个属性A1,A2,A3,A4,A5.要求每一列数值有10%的缺失值,缺失值记为NAN,每一列的数值来自5种不同的分布函数; 2、将所有的缺失值NAN分别填充为该列的均值和最可能出现的数值(取整数); 3、将每列数据Ai分别进行0-1规范化和Z-score规范化; 4、按照等频划分或者等宽划分,把Ai划分成三个分箱A,B,C,并标记每个数据样本在对应Ai的分箱值; 5、将100*5的数据样本在5个属性上进行平行坐标绘图。 的代码
时间: 2023-11-27 11:49:22 浏览: 98
以下是您所需的Python代码:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pandas.api.types import CategoricalDtype
from sklearn.preprocessing import MinMaxScaler, StandardScaler
# 生成100*5的随机数值矩阵
np.random.seed(0)
data = np.random.rand(100, 5)
# 随机生成10%的缺失值
mask = np.random.choice([True, False], size=data.shape, p=[0.1, 0.9])
data[mask] = np.nan
# 填充缺失值为均值和最可能出现的数值
data_mean = pd.DataFrame(data).fillna(pd.DataFrame(data).mean()).values
data_mode = pd.DataFrame(data).fillna(pd.DataFrame(data).mode().iloc[0]).values
data_mode = np.round(data_mode)
# 0-1规范化
scaler = MinMaxScaler()
data_mean_norm = scaler.fit_transform(data_mean)
data_mode_norm = scaler.fit_transform(data_mode)
# Z-score规范化
scaler = StandardScaler()
data_mean_zscore = scaler.fit_transform(data_mean)
data_mode_zscore = scaler.fit_transform(data_mode)
# 将数据划分为三个分箱
bin_labels = ['A', 'B', 'C']
data_bins = np.zeros_like(data_mode, dtype=str)
for i in range(data_mode.shape[1]):
bin_edges = pd.cut(data_mode[:, i], bins=3, labels=bin_labels, retbins=True)[1]
data_bins[:, i] = pd.cut(data_mode[:, i], bins=bin_edges, labels=bin_labels)
# 绘制平行坐标图
fig, axs = plt.subplots(1, 3, figsize=(15, 5))
for i, (data_norm, title) in enumerate(zip([(data_mean_norm, '均值填充'), (data_mode_norm, '众数填充'),
(data_mode_zscore, 'Z-score规范化')], axs)):
data_norm, norm_title = data_norm
df = pd.DataFrame(data_norm, columns=['A1', 'A2', 'A3', 'A4', 'A5'])
df['bins_A1'] = pd.cut(data_mode[:, 0], bins=bin_edges, labels=bin_labels)
df['bins_A2'] = pd.cut(data_mode[:, 1], bins=bin_edges, labels=bin_labels)
df['bins_A3'] = pd.cut(data_mode[:, 2], bins=bin_edges, labels=bin_labels)
df['bins_A4'] = pd.cut(data_mode[:, 3], bins=bin_edges, labels=bin_labels)
df['bins_A5'] = pd.cut(data_mode[:, 4], bins=bin_edges, labels=bin_labels)
df = df.melt(id_vars=['bins_A1', 'bins_A2', 'bins_A3', 'bins_A4', 'bins_A5'], var_name='attribute', value_name='value')
df['value'] = np.round(df['value'], 2)
df = df.sort_values(by=['bins_A1', 'bins_A2', 'bins_A3', 'bins_A4', 'bins_A5'])
palette = dict(zip(bin_labels, ['tab:blue', 'tab:orange', 'tab:green']))
axs[i].set_title(title)
axs[i].set_xticks(range(len(df['attribute'].unique())))
axs[i].set_xticklabels(['A1', 'A2', 'A3', 'A4', 'A5'])
axs[i].set_yticks(range(len(bin_labels)))
axs[i].set_yticklabels(bin_labels)
axs[i].set_ylim(-0.1, 1.1)
for j, (label, group) in enumerate(df.groupby(['bins_A1', 'bins_A2', 'bins_A3', 'bins_A4', 'bins_A5'])):
axs[i].plot(range(len(df['attribute'].unique())), group['value'], color=palette[label[0]], alpha=0.7)
if j == 0:
axs[i].fill_between(range(len(df['attribute'].unique())), 0, group['value'], color=palette[label[0]], alpha=0.2)
elif j == len(df.groupby(['bins_A1', 'bins_A2', 'bins_A3', 'bins_A4', 'bins_A5'])) - 1:
axs[i].fill_between(range(len(df['attribute'].unique())), df['value'].min(), group['value'], color=palette[label[0]], alpha=0.2)
fig.tight_layout()
plt.show()
```
说明:
1. 首先使用`numpy.random.rand`生成100*5的随机数值矩阵,然后使用`numpy.random.choice`生成10%的缺失值掩码,并将对应位置的数据置为`np.nan`。
2. 对于每一列缺失值,使用`pandas.DataFrame.fillna`方法将其分别填充为该列的均值和最可能出现的数值(取整数)。
3. 对于填充后的数据,分别使用`sklearn.preprocessing.MinMaxScaler`和`sklearn.preprocessing.StandardScaler`进行0-1规范化和Z-score规范化。
4. 对于分箱,使用`pandas.cut`方法将每个属性划分为三个等宽的分箱,并标记每个数据样本在对应Ai的分箱值。
5. 最后,使用`matplotlib.pyplot.subplots`方法创建平行坐标图,并使用`matplotlib.pyplot.plot`和`matplotlib.pyplot.fill_between`方法绘制每个分箱内的数据线和区域。其中,使用`pandas.DataFrame.melt`方法将数据转换为长格式,以便于使用`seaborn`等绘图库。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)