一些技巧关于Jupyter和作图
1. 数据导入 导出
#从exelc导入
df=pd.read_excel('D:/1.xls')
#或(使用open可以避免中文路径有时读入报错)
file=open('D:/1.xls')
df=pd.read_excel(file)
#导出到csv(比excel占用存储小)
df.to_csv("D:/test.csv",index=False)
#没有后缀的数据 或 奇怪的数据
pd.read_table('C:/Users/fafa/Desktop/testA/user_data')
pd.read_csv('testA/totalExposureLog.out',sep='\t',names=['ad_request_id','ad_request_time','ad_space_id','user_id','ad_id','Exposure_ad_size','bid','pctr','quality_ecpm','totalEcpm'],memory_map=True)
#### 导入Excel的sheet #############
# 方法一:通过 index 指定工作表
df3 = pd.read_excel(file_name, sheet_name=0)
# 方法二:指定工作表名称
df4 = pd.read_excel(file_name, sheet_name='Sheet1')
#### 导出Excel的sheet #############
#① 导出带有sheet的csv(只能有1个sheet)
df1.to_csv("3.csv",mode='a',index=False)
#② 导出带有sheet的excel
## 命名待被导入的文件
writer = pd.ExcelWriter("2.xlsx")
## 命名待被导入的sheet ###
df1.to_excel(writer,sheet_name='公司维度表',index=False)
df2.to_excel(writer, sheet_name='货物维度表',index=False)
writer.save()
writer.close()
############## 或者可以快速做一个DataFrame #############
df4 = pd.DataFrame({'col1':['1',3],'col2':[2,4]},index=['a','b'])
############### 转置 #############
df2 = pd.DataFrame(df1.values.T, index=df1.columns, columns=df1.index)
df2
##############大文件导入数据,只选取前100行和特定几列#############
subset_columns = ['Job #', 'Doc #', 'Borough', 'Initial Cost', 'Total Est. Fee']
df = pd.read_csv('文件路径', nrows=100, usecols=subset_columns)
df.head()
数据类型的转换
大文件分批读取并导出为多个小文件方法1,方法2
2. 查看数据情况:
#查看前5行
df.head(5)
#df.head()
#查看数据量
df.describe()
df.count()
#查看列名
df.columns
3. 列名修改
##########给没有表头的数据补上列名 或者直接暴力更改列名##################
df.columns=['广告id','创建时间','广告账户id','商品id','商品类型','广告行业id','素材尺寸']
##########更改列名更改列名更改列名################
dataA=df.rename(columns={"姓名":"最高分得主A","得分":"A题"},axis=1) #axis=1按列改名
########选择需要的特征,更改列的顺序##############
df1=df1[['广告id','创建时间','商品id', '商品类型', '广告行业id', '素材尺寸']]
其他的参考:列名修改 索引修改 内容修改 数据类型转换 时间转换
[特征作图](https://www.cnblogs.com/gczr/p/6802948.html)
4. 处理脏数据
######################### 处理脏数据 ##############################
############①找出一列中的不同元素,并按照最大值输出#####
import pandas as pd
import numpy as np
df=pd.DataFrame({"id":["1","2","3,4"]})
df
#仅保留最大值
def max_str(t):
a=[int(i) for i in t]
return max(a)
df["id_max"]=df["id"].str.split(",").map(max_str)
df
############②找出一列中的不同元素,并按照最大值输出#####
#清理带有“,”的脏数据
df2=df.astype(str)#令所有内容变成字符串
#清理广告行业id的脏数据
df3=df2[df2["广告行业id"].str.contains(",")]#包含逗号的数据
L1=list(df3.广告行业id)#包含逗号的数据做成一个列表list1
L2=list(df2.广告行业id)#全部数据做成一个列表list2
L3=list(set(L2)^set(L1))#列表求差集的方法:去掉脏数据的正常数据集合
df[df.广告行业id.isin(L3)]#isin()搜寻正常数据集合的最终结果
#直接方法: ~isin()搜寻不包含异常值的最终结果
df[~df.广告行业id.isin(L1)]
############③找出一列中的不同元素,拆分输出#####
import pandas as pd
df=pd.DataFrame([["a","15"],["b,c","16"]],columns=["姓名","分数"])
df.set_index("分数")["姓名"].str.split(",",expand=True).stack().reset_index(level=1,drop=True).reset_index(name="姓名")
#############④处理空值NaN#######################
import pandas as pd,numpy as np
df=pd.DataFrame({'姓名':'张三 李四 王五 赵六 孙七 马八'.split(),'年龄':[18,np.nan,22,23,11,np.nan]})
#找出空值
isnull()
notnull()
#填充空值NaN为0 或者其他
df.fillna(0)
#删去指定列空值所在行或列删除空值行(axis=0)或列(axis=0)
df.dropna(axis=0, how="any", thresh=None, subset=None, inplace=False)
#当然可以直接简写
df.dropna()
#删去指定列空值所在行
df[np.isnan(df.年龄)==False ]
#值替换
df.replace()
特征选择 帖子筛选
5. 关联合并
######################### 关联两个表 merge ##########################
df3=pd.merge(df1,df2,on='id') #按照id关联(两表id交集)
#########################合并两个表concat###########################
df3=pd.concat([df1,df2],axis=0,ignore_index=False) #axis=0按行合并
#例子:把"赛题A"增到"A总" 并去除
dfA=pd.concat([df1,df2]).drop_duplicates()
集合的交并补
list1 = [1,2,3]
list2 = [3,4,5]
#首先把数据类型 修改为集合类型
set1 = set(list1)
set2 = set(list2)
print(set1&set2) #交集
print(set1^set2) #补集
set(1)-set(2) #余集
pandas 中,AND 条件的运算符为 & ,OR 条件的运算符为 |
6. 去重(按照ID)
df=df.drop_duplicates()#完全相等的去重
dfA=dfA.drop_duplicates("ID")#默认保留第一条数据
df=df.drop_duplicates(["班级","姓名"])#按照某两列去重
7. 排序+重置索引
#排序(按照最终分数) ascending=False表示从大到小Ture表示从小到大
df1=df.sort_values(by="总分",ascending=False)
#多列排序(先排"队伍总分",再“个人成绩”)
df1=df.sort_values(by=["队伍总分","个人成绩"],ascending=(False,False))
![](https://img.haomeiwen.com/i17163699/3a72a99bb52bca91.png)
![](https://img.haomeiwen.com/i17163699/43ea61f3eb5a82f7.png)
#重置索引
dfA=dfA.reset_index(drop=True)
#让索引从1开始
df.index = df.index+1
8.条件筛选+分组统计+分组计数
#找出满足条件的数据(年月相同,曝光日为创建的第二日)
df=df3[df3.创建日期.map(int)+1==df3.广告请求日期.map(int)]
# 且& 或| 非not
df=df3[(df3['售价']>=2000) & (df3['售价']<2000)]
#按照 个数 统计 队伍
df.groupby(["队伍"]).size()
#按照max得分统计队伍
df2=df.groupby(["队伍名称"],as_index=False)["得分"].max()
#按照sum得分统计队伍
df2=df.groupby(["队伍"],as_index=False)["得分"].sum()
#统计"相同ID"和"创建时间"的数据计数 (按照"广告id" 和 "创建日期"分组并计数) 即"次日曝光量"
#方法一
df['次日曝光量']=df.groupby(['广告id','创建日期'])['广告id'].transform(len)
df=df.drop_duplicates("产品") #去重
df=df.reset_index(drop=True) #重置索引
#方法二
counts=df.groupby(['id','日期']).size() #获得'id' '日期' "次日曝光量" 三列 这样的表counts
counts=df.reset_index(name='label') #重置索引(否则表头高度不一致)
#df=df.merge(counts,how='inner',on=['id','日期'])#按照两列关联到一起,即得到“日曝光量”这一列
实例:统计产品销量
9. 像excel一样操作: 按照某种条件 增加一列
①--------IF函数--------
#对应的Excel语言: =IF(条件,分支1,分支2)
df1['category'] = np.where(df1['total'] > 200000, 'A', 'B')
②--------合并两列 逗号间隔--------
#先来转换一下数据类型(也可以用df["map针对某列"].map(str))
df=df.astype('str')
df['AAA']=df['A'].str.cat(df['B'],sep=',')
③--------求最值 求和--------
#方法一
df['c']=df.min(axis=1)
#如果是多列,那么先挑出来需要的列
df['d']=df[['c','B']].max(axis=1)
#方法二
df['c']=np.min(df,axis=1)
#或者 .values返回的是数组
df['c']=np.min(df.values,axis=1)
#方法三apply()
df['q']=df.apply(min,axis=1)
#增加一列 求和
df["总分"]=df.sum(axis=1)
④--------循环方法--------
def F(a):
if a[1]<a[2]:
s='甲'
if a[1]>a[2]:
s='乙'
return s
df["完成人"]=[F(df.iloc[i]) for i in range(len(df.index))]
⑤--------apply()方法--------
#### 合并两列并逗号间隔 ###########
def F(t):
s=str(t[0])+','+str(t[1])
return s
df['CC']=df.apply(F,axis=1)
#def F(t):
# s=t[0],t[1]
# return s
#df['CC']=df.apply(F,axis=1)
# 提取d[a]中前2位 到新的一列#
df[b] = df[a].apply(lambda x : x[:2])
def func(x):
if x>20:
return '20+k'
else:
return '0-20k'
position.apply(lambda x:func(x.avg),axis=1).head()
温馨提示:整列操作 要快于 apply() 操作
groupby, agg, apply用法
pandas.apply实测使用方法
10. 时间类
(1)计时器
################## 计时器 #######################################
import time
starttime = time.time()
#time.sleep(2.1)#延时2.1s
endtime = time.time()
dtime = endtime - starttime
print("程序运行时间:%.8s s" % dtime) #显示到微秒
(2)时间戳
############################## 时间戳 ###################################
#首先调用包,创建时间戳列
import pandas as pd
df=pd.DataFrame({"时间戳":[1529648412,1529648412]})
#时间戳[按照周期加减一天](https://blog.csdn.net/lilongsy/article/details/80242427?utm_source=blogxgwz7)
#比较好的[参考](https://blog.csdn.net/weixin_33861800/article/details/88001086)
###############①方法 时间戳(1529648412)列→(20180622) ##########################
import time
df['时间'] = df['时间戳'] .apply(lambda x:time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(x)))
df
###############②方法 时间戳(1529648412)列→(20180622)
df['时间']=pd.to_datetime(df['时间戳'],unit='s') #→(2018-06-22 06:20:12)
##(2018-06-22 06:20:12) → (2018-06-22)
df=df.set_index('时间') #把时间设置为索引(为了转化)
df["当日日期"]=df.index.date #转化为当日日期(2018-06-22)
df=df.reset_index()
###############③方法 时间戳(1529648412)列→(20180622)
################# [Python 时间戳→当日/次日 日期](https://www.jianshu.com/p/e4101420496f) ########################
####时间戳(1529648412)→(2018-06-22 06:20:12)→(2018-06-22)
df['时间']=pd.to_datetime(df['时间戳'],unit='s')
df=df.set_index('时间') #把时间设置为索引(为了转化)
df["date"]=df.index.date #转化为日期(2018-06-22)
df=df.reset_index()
#####(2018-06-22)→年月日三列→(20180622)
df["年"]=df["date"].map(str).str[0:4]
df["月"]=df["date"].map(str).str[5:7]
df["日"]=df["date"].map(str).str[8:]
df["日期"]=df["年"].map(str)+df["月"]+df["日"]
df
#####时间戳(1529648412)列→年月日三列→为(20180622) (暂时行不通 )
df['year'] =df['时间戳'].apply(lambda x: time.localtime(x).tm_year)
df['month'] = df['时间戳'].apply(lambda x: time.localtime(x).tm_mon)
df['day'] =df['时间戳'].apply(lambda x: time.localtime(x).tm_mday)
#暂时行不通(2018+6+22): df3["创建日期"]=df3["year"].map(str)+df3["month"].map(str)+df3["day"].map(str)
###################④方法:任意时间格式→时间戳函数
from datetime import datetime
#任意时间格式→时间戳函数
def time2stamp(cmnttime):
cmnttime=datetime.strptime(cmnttime,'%Y%m%d') #这里可以更改任意格式:'%Y-%m-%d %H:%M:%S'
stamp=int(datetime.timestamp(cmnttime))
return stamp
df['日期时间戳']=df['日期'].apply(time2stamp)
模型
#选取数据
data=df
#划分数据集
from sklearn.model_selection import train_test_split
train, test = train_test_split(data, test_size=0.2, random_state=2021)
################### 决策树及其集成模型 #############################################################
#####################################################################################################
########################################### 决策树####################################################
from sklearn.tree import DecisionTreeClassifier
model_1 = DecisionTreeClassifier(max_depth=None, min_samples_split=2,random_state=0)
#定义数据和标签 检测数据自动划分交叉验证的准确率
data=train.iloc[:,:-1]
label=train.iloc[:,-1]
scores1 = cross_val_score(model_1, data, label)
print("决策树自动划分交叉验证准确率",scores1.mean())
#用训练集拟合模型
model_1.fit(data,label)
#用训练好的模型 预测 训练集本身
scores2 =model_1.score(train.iloc[:,:-1],train.iloc[:,-1])
print("预测训练集全体的准确率",scores2)
#用训练好的模型 预测 测试集
scores3 =model_1.score(test.iloc[:,:-1],test.iloc[:,-1])
print("预测测试集的准确率",scores3)
y_pred=model_1.predict(test.iloc[:,:-1])
y_true=test.iloc[:,-1]
#混淆矩阵
cm = confusion_matrix(y_true, y_pred)
cm
#########绘制混淆矩阵
#先定义类别变量
classes=set(y_true)
plot_confusion_matrix(cm, 'confusion_matrix.png', title='confusion matrix')
######################################################################################################
############################################### 随机森林 ###############################################
model_2 = RandomForestClassifier(n_estimators=10, max_depth=None,min_samples_split=2, random_state=0)
#定义数据和标签 检测数据自动划分交叉验证的准确率
data=train.iloc[:,:-1]
label=train.iloc[:,-1]
scores1 = cross_val_score(model_2, data, label)
print("随机森林自动划分交叉验证准确率",scores1.mean())
#用训练集拟合模型
model_2.fit(data,label)
#用训练好的模型 预测 训练集本身
scores2 =model_2.score(train.iloc[:,:-1],train.iloc[:,-1])
print("预测训练集全体的准确率",scores2)
#用训练好的模型 预测 测试集
scores3 =model_2.score(test.iloc[:,:-1],test.iloc[:,-1])
print("预测测试集的准确率",scores3)
y_pred=model_2.predict(test.iloc[:,:-1])
y_true=test.iloc[:,-1]
#混淆矩阵
cm = confusion_matrix(y_true, y_pred)
cm
#########绘制混淆矩阵
#先定义类别变量
classes=set(y_true)
plot_confusion_matrix(cm, 'confusion_matrix.png', title='confusion matrix')
######################################################################################################
###################################### ExtraTree分类器集合 ####################################
from sklearn.ensemble import ExtraTreesClassifier
model_2 = ExtraTreesClassifier(n_estimators=10, max_depth=None,min_samples_split=2, random_state=0)
#定义数据和标签 检测数据自动划分交叉验证的准确率
data=train.iloc[:,:-1]
label=train.iloc[:,-1]
scores1 = cross_val_score(model_2, data, label)
print("极端随机树自动划分交叉验证准确率",scores1.mean())
#用训练集拟合模型
model_2.fit(data,label)
#用训练好的模型 预测 训练集本身
scores2 =model_2.score(train.iloc[:,:-1],train.iloc[:,-1])
print("预测训练集全体的准确率",scores2)
#用训练好的模型 预测 测试集
scores3 =model_2.score(test.iloc[:,:-1],test.iloc[:,-1])
print("预测测试集的准确率",scores3)
y_pred=model_2.predict(test.iloc[:,:-1])
y_true=test.iloc[:,-1]
#混淆矩阵
cm = confusion_matrix(y_true, y_pred)
cm
#########绘制混淆矩阵
#先定义类别变量
classes=set(y_true)
plot_confusion_matrix(cm, 'confusion_matrix.png', title='confusion matrix')
############################################################################################################
###################### 回归模型做预测 ########################
##from sklearn.linear_model import LogisticRegression
##from sklearn.linear_model import SGDClassifier
##
## penalty:正则化 l2/l1
## C :正则化强度
## multi_class:多分类时使用 ovr: one vs rest
##lor = LogisticRegression(penalty='l1',C=100,multi_class='ovr')
##lor.fit(X_std_train,y_train)
##print(lor.score(X_std_test,y_test))
##
##sgdv = SGDClassifier(penalty='l1')
##sgdv.fit(X_std_train,y_train)
##print(sgdv.score(X_std_test,y_test))
##################### 回归模型做预测 ##########################
################################################# 逻辑回归模型 ###################################################
from sklearn.linear_model import LogisticRegression
# multi_class:多分类时使用 ovr: one vs rest
model_4 = LogisticRegression(multi_class='ovr')
#定义数据和标签 检测数据自动划分交叉验证的准确率
data=train.iloc[:,:-1]
label=train.iloc[:,-1]
scores1 = cross_val_score(model_4, data, label)
print("逻辑回归自动划分交叉验证准确率",scores1.mean())
#用训练集拟合模型
model_4.fit(data,label)
#用训练好的模型 预测 训练集本身
scores2 =model_4.score(train.iloc[:,:-1],train.iloc[:,-1])
print("预测训练集全体的准确率",scores2)
#用训练好的模型 预测 测试集
scores3 =model_4.score(test.iloc[:,:-1],test.iloc[:,-1])
print("预测测试集的准确率",scores3)
y_pred=model_4.predict(test.iloc[:,:-1])
y_true=test.iloc[:,-1]
#混淆矩阵
cm = confusion_matrix(y_true, y_pred)
cm
#########绘制混淆矩阵
#先定义类别变量
classes=set(y_true)
plot_confusion_matrix(cm, 'confusion_matrix.png', title='confusion matrix')
############################################### 随机梯度下降分类器模型 #################################################
from sklearn.linear_model import SGDClassifier
model_5 = SGDClassifier()
#定义数据和标签 检测数据自动划分交叉验证的准确率
data=train.iloc[:,:-1]
label=train.iloc[:,-1]
scores1 = cross_val_score(model_5, data, label)
print("随机梯度下降分类器自动划分交叉验证准确率",scores1.mean())
#用训练集拟合模型
model_5.fit(data,label)
#用训练好的模型 预测 训练集本身
scores2 =model_5.score(train.iloc[:,:-1],train.iloc[:,-1])
print("预测训练集全体的准确率",scores2)
#用训练好的模型 预测 测试集
scores3 =model_5.score(test.iloc[:,:-1],test.iloc[:,-1])
print("预测测试集的准确率",scores3)
y_pred=model_5.predict(test.iloc[:,:-1])
y_true=test.iloc[:,-1]
#混淆矩阵
cm = confusion_matrix(y_true, y_pred)
cm
#########绘制混淆矩阵
#先定义类别变量
classes=set(y_true)
plot_confusion_matrix(cm, 'confusion_matrix.png', title='confusion matrix')
################################################# 神经网络多层感知器模型 ###################################################
from sklearn.neural_network import MLPClassifier
model_6 = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5,), random_state=1)
#定义数据和标签 检测数据自动划分交叉验证的准确率
data=train.iloc[:,:-1]
label=train.iloc[:,-1]
scores1 = cross_val_score(model_6, data, label)
print("神经网络多层感知器分类器自动划分交叉验证准确率",scores1.mean())
#用训练集拟合模型
model_6.fit(data,label)
#用训练好的模型 预测 训练集本身
scores2 =model_6.score(train.iloc[:,:-1],train.iloc[:,-1])
print("预测训练集全体的准确率",scores2)
#用训练好的模型 预测 测试集
scores3 =model_6.score(test.iloc[:,:-1],test.iloc[:,-1])
print("预测测试集的准确率",scores3)
y_pred=model_6.predict(test.iloc[:,:-1])
y_true=test.iloc[:,-1]
#混淆矩阵
cm = confusion_matrix(y_true, y_pred)
cm
#########绘制混淆矩阵
#先定义类别变量
classes=set(y_true)
plot_confusion_matrix(cm, 'confusion_matrix.png', title='confusion matrix')
决策树可视化
https://blog.csdn.net/sanjianjixiang/article/details/102796374
https://www.zhihu.com/question/65472459
If you are interested in this topic.
You can get in touch with me.
18234056952(Tel wechat qq)
网友评论