数据处理
import pandas as pd
import numpy as np
# 导入数据
df1=pd.read_excel('附件2:302家无信贷记录企业的相关数据.xlsx',sheet_name='企业信息')
df2=pd.read_excel('附件2:302家无信贷记录企业的相关数据.xlsx',sheet_name='进项发票信息')
df3=pd.read_excel('附件2:302家无信贷记录企业的相关数据.xlsx',sheet_name='销项发票信息')
# 数据转换
map_type1 = {"有效发票":1, "作废发票":0} # 类别转换为数字1 0
df2.loc[:, "发票状态"] = df2['发票状态'].map(map_type1)
map_type2 = {"有效发票":1, "作废发票":0} # 类别转换为数字1 0
df3.loc[:, "发票状态"] = df3['发票状态'].map(map_type2)
# 剔除df2中异常值
# 指定要处理的列的索引
columns_index = ['金额', '税额', '价税合计']
# 遍历每一列,计算3σ原则的异常值范围并删除异常值
for i in columns_index:
mean = df2[i].mean()
std = df2[i].std()
lower_bound = mean - 3 * std
upper_bound = mean + 3 * std
# 删除异常值
df2 = df2[(df2[i] >= lower_bound) & (df2[i] <= upper_bound)]
# 对df2中企业代码列进行分组
grouped = df2.groupby('企业代号')
# 对分组后的数据中'金额', '税额','价税合计'进行描述统计,衍生出24种变量
df2_description_1 = grouped[['金额', '税额','价税合计']].describe()
# 对分组的数据中发票状态进行描述统计,衍生出4种变量
df2_description_2 = grouped[['发票状态']].describe()
# 合并df2_description_1与df2_description_2
merged_df2 = pd.concat([df2_description_1,df2_description_2], axis=1)
# 将df1、merged_df2合并,以‘企业代号’为连接键
merged_data=pd.merge(df1,merged_df2,left_on='企业代号',right_on='企业代号')
# 同理处理df3
# 剔除df3中异常值
# 指定要处理的列的索引
columns_index = ['金额', '税额', '价税合计']
# 遍历每一列,计算3σ原则的异常值范围并删除异常值
for i in columns_index:
mean = df3[i].mean()
std = df3[i].std()
lower_bound = mean - 3 * std
upper_bound = mean + 3 * std
# 删除异常值
df3 = df3[(df3[i] >= lower_bound) & (df3[i] <= upper_bound)]
grouped = df3.groupby('企业代号')
df3_description_1 = grouped[['金额', '税额','价税合计']].describe()
df3_description_2 = grouped[['发票状态']].describe()
merged_df3 = pd.concat([df3_description_1,df3_description_2], axis=1)
merged_data=pd.merge(df1,merged_df3,left_on='企业代号',right_on='企业代号')
# 导出数据
merged_data.to_excel('./附件2_数据处理.xlsx')