select symbol, "price.*" from stocks :使用正则表达式来指定列查询

select count(*), avg(salary) from emplyee: 聚合函数

select count(distinct col) from stocks:去重后的数目

嵌套查询:

from(select upper(name), salary,deductions["Federal Taxes"] as fed_taxes,round(salary*(1-deductions["Federal Taxes"])) as salary_minus from employees) e select e.name, e.salary_mines,where e.salary_minus>70000;

case...when...then...查询

like语句查询:

Rlike语句

group by 语句

group by 语句通常会和聚合函数一块使用,按照一个或者多个列对结果进行分组,然后对每个分组进行聚合操作。

Hive中的order by 和sort by 的区别:

order by执行的是一个全局排序,也就是说也就是说所有的数据都是通过一个Reducer来排序的,对于大数据集来说,话费很长世间,而sort by是局部排序,在每个Reducer中对数据进行排序,也就是说在每个Reducer中是有序的,但是所有Reducer合起来,就是局部有序。

Union all

Union all 可以将2个或者多个表进行合并。但是每一个Union 子查询必须有相同的列,而且每个字段的类型必须是一样的。

下面是hive当中的一些常用函数:

数据函数,集合函数,类型转化函数,日期函数,,条件函数,字符函数,聚合函数,表生成函数。

from_unixtime(bigint unixtime[, string format]):将时间秒值转化为Format格式的时间

例如:from_unixtime(1250111000,"yyyy-MM-dd") 得到2009-03-12

unix_timestamp(string date, string pattern):将format格式的时间字符串转化为时间戳:

例如:unix_timestamp('2009-03-20 11:30:01') = 1237573801

python工具:

数据预览:

df.head(n); df.info(); df.describe(); df.tail()

df.columns:行名

df.index:列名

train.shape

train.dtypes

pd.concat([train, test],ignore_index=True)

only_western_europe_10 = (reprot_2016_df['地区'] == 'Western Europe') & (reprot_2016_df['排名'] > 10)

df.set_index(['Region', 'Country']):设置层级索引

数据清洗

log_data.isnull():是否缺失

log_data[log_data['volume'].notnull()]:取出volume不为空的数据

log_data.fillna(0):填充缺失数据为0

log_data.dropna():去掉有缺失数据的记录

log_data.ffill():以前面的数据填充

log_data.bfill():以后面的数据填充

data.duplicated():判断是否重复

data.drop_duplicates():去除重复数据

map:使用

meat_to_animal = {
'bacon': 'pig',
'pulled pork': 'pig',
'pastrami': 'cow',
'corned beef': 'cow',
'honey ham': 'pig',
'nova lox': 'salmon'
}

lowercased = data['food'].str.lower()
data['animal'] = lowercased.map(meat_to_animal)

或者:

data['food'].map(lambda x: meat_to_animal[x.lower()])

# 将-999替换为空值
data.replace([-999, -1000], np.nan):将列表里的数替换为nan

split_df = data.str.split('@', expand=True):str各种函数

pd.merge(staff_df, student_df, how='outer', on='姓名'):合并df,可选择左右内外连接

staff_df['员工姓名'].apply(lambda x: x[0]):apply的使用

report_data.groupby('Region')grouped['Happiness Score'].mean():后面的聚合函数是对每个分组进行操作的

# 迭代groupby对象
for group, frame in grouped:
mean_score = frame['Happiness Score'].mean()
max_score = frame['Happiness Score'].max()
min_score = frame['Happiness Score'].min()

grouped.agg({'Happiness Score': np.mean, 'Happiness Rank': np.max}):分组的聚合函数

grouped['Happiness Score'].agg([mean, amax, amin, std]):分组的聚合函数

绘图:matplotlib 和 seaborn工具:

%matplotlib notebook:魔法命令

plt.style.available:可用的绘图样式

plt.style.use('seaborn-colorblind'):设置绘图样式

df.plot():分别以每一列为纵轴,索引为横轴,画曲线图,并以图例区别开来

df.plot('A', 'B', kind='scatter'):指定A为横轴,B为纵轴

df.plot(kind='box'):kind可以为hist,kde

pd.plotting.scatter_matrix(iris):散点距阵,查看各个特征之间的相关性

sns.pairplot(iris, hue='Name', diag_kind='kde'):查看各个特征之间的相关性

特征工程:

归一化:

scaler = MinMaxScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

标签编码和独热编码:

首先训练集:

# 在训练集上进行编码操作
label_enc1 = LabelEncoder() # 首先将male, female用数字编码
one_hot_enc = OneHotEncoder() # 将数字编码转换为独热编码

label_enc2 = LabelEncoder() # 将low, middle, high用数字编码

tr_feat1_tmp = label_enc1.fit_transform(X_train[:, 0]).reshape(-1, 1) # reshape(-1, 1)保证为一维列向量
tr_feat1 = one_hot_enc.fit_transform(tr_feat1_tmp)
tr_feat1 = tr_feat1.todense()

tr_feat2 = label_enc2.fit_transform(X_train[:, 1]).reshape(-1, 1)

X_train_enc = np.hstack((tr_feat1, tr_feat2))

然后再测试集上:

te_feat1_tmp = label_enc1.transform(X_test[:, 0]).reshape(-1, 1) # reshape(-1, 1)保证为一维列向量
te_feat1 = one_hot_enc.transform(te_feat1_tmp)
te_feat1 = te_feat1.todense()

te_feat2 = label_enc2.transform(X_test[:, 1]).reshape(-1, 1)

X_test_enc = np.hstack((te_feat1, te_feat2))

模型持久化:

# 保存模型到硬盘
model_path2 = './trained_model2.pkl'
joblib.dump(best_model, model_path2)

model = joblib.load(model_path2)

日期特征处理:

train['created'] = pd.to_datetime(train['created'])
train['date'] = train['created'].dt.date
train["year"] = train["created"].dt.year
train['month'] = train['created'].dt.month
train['day'] = train['created'].dt.day

data[v].value_counts():列举不同的取值,以及每种取值的次数

data.drop(['Loan_Amount_Submitted','Loan_Tenure_Submitted'],axis=1,inplace=True):删除某列

df_train_origin[['temp','weather','windspeed','day', 'month', 'hour','count']].corr():相关性

pd.get_dummies(all_df['MSSubClass'], prefix='MSSubClass'):独热编码一键搞定

all_dummy_df.isnull().sum().sort_values(ascending=False):统计各个字段的空值数目

all_dummy_df.isnull().sum().sum():各个字段的总空值数

合并之后的数据重新分开:

dummy_train_df = all_dummy_df.loc[train_df.index]
dummy_test_df = all_dummy_df.loc[test_df.index]

df.unstack() 行索引→列索引

df.stack() 列索引→行索引

数据分析常用的python工具和SQL语句的更多相关文章

  1. Python 数据分析:让你像写 Sql 语句一样,使用 Pandas 做数据分析

    Python 数据分析:让你像写 Sql 语句一样,使用 Pandas 做数据分析 一.加载数据 import pandas as pd import numpy as np url = ('http ...

  2. MySQL05-- 客户端工具及SQL语句

    目录 MySQL客户端工具及SQL语句 一.客户端命令介绍 二.接收用户的SQL语句 三.字符集定义 四.字符集设置 五.select的高级用法(扩展) MySQL客户端工具及SQL语句 一.客户端命 ...

  3. 50个常用的笔试、面试sql语句

    50个常用的笔试.面试sql语句 2009-12-17 15:05   Student(S#,Sname,Sage,Ssex) 学生表Course(C#,Cname,T#) 课程表SC(S#,C#,s ...

  4. 微软官方提供的用于监控MS SQL Server运行状况的工具及SQL语句

    Microsoft SQL Server 2005 提供了一些工具来监控数据库.方法之一是动态管理视图.动态管理视图 (DMV) 和动态管理函数 (DMF) 返回的服务器状态信息可用于监控服务器实例的 ...

  5. sql server 数据分析优化实战(一)——SQL语句优化

    前言 在我们进行数据分析的时候,首要的目标是根据业务逻辑,通过编写SQL代码得到我们想要的结果,这是毋庸置疑的.一般情况下,由于我们分析的数据量比较少,体会不出SQL语句各种写法的性能优劣,对SQL代 ...

  6. mysql详解常用命令操作,利用SQL语句创建数据表—增删改查

    关系型数据库的核心内容是 关系 即 二维表 MYSQL的启动和连接show variables; [所有的变量] 1服务端启动 查看服务状态 sudo /etc/init.d/mysql status ...

  7. 【python】提取sql语句中的表名

    前言 最近刚学python,写一个小工具时需要提取sql语句中表名,查询一番后找到一篇文章挺不错的,mark一下 PS.那篇文章是转载的,且没有标注转载自哪里 正文 import ply.lex as ...

  8. python快速导出sql语句(mssql)的查询结果到Excel,解决SSMS无法加载大字段的问题

    遇到一个尴尬的问题,SSMS的GridView对于大字段的(varchar(max),text之类的),支持不太友好的,超过8000个长度之外的字符,SSMS的表格是显示不出来的(当然也就看不到了), ...

  9. MySql数据库转设计文档(mysql-font工具和sql语句导出)

    一.工具导出 1.使用的是MySQL-Front工具,这个工具使用非常方便,尤其是导出数据的时候,几百万的数据一两分钟就导完了,推荐使用. MySQL-Front下载(只有3.93M):http:// ...

随机推荐

  1. ubuntu+anaconda

    1.下载anaconda 查看ubuntu是32位还是64位 命令: uname -m 如果显示i686,你安装了32位操作系统 如果显示 x86_64,你安装了64位操作系统 uname -a 查看 ...

  2. VS Code插件

    VS Code下载地址: https://code.visualstudio.com/ 1.view in browser   和  Open-In-Browser  安装可在编辑器中打开html,在 ...

  3. [java]转:String Date Calendar之间的转换

    String Date Calendar之间的转换 String Date Calendar  1.Calendar 转化 String Calendar calendat = Calendar.ge ...

  4. mysql排序的中文首字母排序和自定义排序

    select * FROM organ_new where city_code = 'SZ0755' and organ_type = 'H' and state = '1' ORDER BY FIE ...

  5. leetcode-algorithms-24 Swap Nodes in Pairs

    leetcode-algorithms-24 Swap Nodes in Pairs Given a linked list, swap every two adjacent nodes and re ...

  6. 解决gitHub下载速度慢的问题

    转载:http://blog.csdn.net/x_studying/article/details/72588324 github被某个CDN被伟大的墙屏蔽所致. 解决方法: 1.访问http:// ...

  7. 前端基础之CSS的引入+HTML标签选择器+CSS操作属性

    clear:left/ringt属性 CSS:语法形式上由选择器+以及一条或多条声明组成:选择器查找到指定的html标签后,使用css属性设置html标签的样式:                   ...

  8. python3+ftplib实现ftp客户端

    一.程序说明 1.1 程序实现关键点 python实现ftp客户端,主要会遇到以下四个问题: 第一个问题是使用什么包实现----我们这里是使用标准库中的ftplib 第二个问题是怎么连接登录ftp服务 ...

  9. 谈一谈JUnit神奇的报错 java.lang.Exception:No tests found matching

    最近在学习Spring+SpringMVC+MyBatis,一个人的挖掘过程确实有点艰难,尤其是有一些神奇的报错让你会很蛋疼.特别是接触一些框架还是最新版本的时候,会因为版本问题出现很多错误,欢迎大家 ...

  10. linux下文件内容查找 转

    find | xargs grep test find命令和xargs命令 网友:wuye_chinaunix 发布于: : (共有条评论) 查看评论 | 我要评论 青云 分配文件 - -| 回首页 ...