supermarket_sales - sheet1.csv文件数据预处理代码
时间: 2024-03-15 16:42:18 浏览: 23
好的,下面是 supermarket_sales - sheet1.csv 文件数据预处理的代码示例:
```python
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
# 读取 csv 文件中的数据
df = pd.read_csv('supermarket_sales - sheet1.csv')
# 处理缺失值
df = df.dropna() # 删除含有缺失值的行
# 处理异常值
Q1 = df.quantile(0.25)
Q3 = df.quantile(0.75)
IQR = Q3 - Q1
df = df[~((df < (Q1 - 1.5 * IQR)) | (df > (Q3 + 1.5 * IQR))).any(axis=1)] # 删除异常值
# 数据类型转换
df['Quantity'] = df['Quantity'].astype('int')
df['Unit price'] = df['Unit price'].astype('float')
df['Tax 5%'] = df['Tax 5%'].astype('float')
df['Total'] = df['Total'].astype('float')
# 数据归一化
scaler = MinMaxScaler()
df[['Quantity', 'Unit price', 'Tax 5%', 'Total']] = scaler.fit_transform(df[['Quantity', 'Unit price', 'Tax 5%', 'Total']])
# 特征选择
corr_matrix = df.corr() # 计算相关系数矩阵
selected_features = corr_matrix['Total'].sort_values(ascending=False)[:4].index.tolist() # 选择与 Total 最相关的前四个特征
df = df[selected_features]
# 保存数据
df.to_csv('processed_supermarket_sales.csv', index=False)
```
这段代码的作用是将 supermarket_sales - sheet1.csv 文件中的数据进行缺失值删除、异常值删除、数据类型转换、数据归一化、特征选择和保存等预处理步骤,最终将处理后的数据保存到新的 csv 文件中。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![apk](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)