用python画熊猫

Python短裤 (Python Shorts)

Pandas is one of the best data manipulation libraries in recent times. It lets you slice and dice, groupby, join and do any arbitrary data transformation. You can take a look at this post, which talks about handling most of the data manipulation cases using a straightforward, simple, and matter of fact way using Pandas.

熊猫是最近最好的数据处理库之一。 它使您可以切片,切块,分组,加入并进行任意数据转换。 您可以看一下这篇文章 ,该文章讨论了使用Pandas通过一种简单,简单且实际的方式处理大多数数据处理案例。

But even with how awesome pandas generally is, there sometimes are moments when you would like to have just a bit more. Say you come from a SQL background in which the same operation was too easy. Or you wanted to have more readable code. Or you just wanted to run an ad-hoc SQL query on your data frame. Or, maybe you come from R and want a replacement for sqldf.

但是,即使一般的熊猫都很棒,有时您还是会想要多一点。 假设您来自SQL背景,在该背景下,同一操作太容易了。 或者您想拥有更具可读性的代码。 或者,您只想在数据框上运行临时SQL查询。 或者,也许您来自R并想要替代sqldf.

For example, one of the operations that Pandas doesn’t have an alternative for is non-equi joins, which are quite trivial in SQL.

例如,Pandas没有替代品的操作之一是非等额联接,这在SQL中非常简单。

In this series of posts named Python Shorts, I will explain some simple but very useful constructs provided by Python, some essential tips, and some use cases I come up with regularly in my Data Science work.

在这一系列名为Python Shorts的文章中,我将解释一些由Python提供的简单但非常有用的结构,一些基本技巧以及一些在数据科学工作中定期提出的用例。

This post is essentially about using SQL with pandas Dataframes.

这篇文章实质上是关于将SQL与pandas Dataframes一起使用。

但是,什么是非等额联接,为什么我需要它们? (But, what are non-equi joins, and why would I need them?)

Let’s say you have to join two data frames. One shows us the periods where we offer some promotions on some items. And the second one is our transaction Dataframe. I want to know the sales that were driven by promotions, i.e., the sales that happen for an item in the promotion period.

假设您必须连接两个数据框。 一个向我们展示了我们在某些项目上提供促销的时期。 第二个是我们的交易数据框。 我想知道由促销推动的销售,即促销期间某项目发生的销售。

We can do this by doing a join on the item column as well as a join condition (TransactionDt≥StartDt and TransactionDt≤EndDt). Since now our join conditions have a greater than and less than signs as well, such joins are called non-equi joins. Do think about how you will do such a thing in Pandas before moving on.

我们可以通过在item列上进行item以及联接条件( TransactionDt≥StartDtTransactionDt≤EndDt )来实现。 从现在开始,我们的联接条件也具有大于和小于的符号,这种联接称为非等联接。 在继续之前,请考虑一下如何在熊猫中做这样的事情。

熊猫解决方案 (The Pandas Solution)

So how will you do it in Pandas? Yes, a Pandas based solution exists, though I don’t find it readable enough.

那么,您将如何在Pandas中做到这一点? 是的,存在基于Pandas的解决方案,尽管我认为它不够可读。

Let’s start by generating some random data to work with.

让我们从生成一些随机数据开始。

import pandas as pd
import random
import datetimedef random_dt_bw(start_date,end_date):days_between = (end_date - start_date).daysrandom_num_days = random.randrange(days_between)random_dt = start_date + datetime.timedelta(days=random_num_days)return random_dtdef generate_data(n=1000):items = [f"i_{x}" for x in range(n)]start_dates = [random_dt_bw(datetime.date(2020,1,1),datetime.date(2020,9,1)) for x in range(n)]end_dates = [x + datetime.timedelta(days=random.randint(1,10)) for x in start_dates]offerDf = pd.DataFrame({"Item":items,"StartDt":start_dates,"EndDt":end_dates})transaction_items = [f"i_{random.randint(0,n)}" for x in range(5*n)]transaction_dt = [random_dt_bw(datetime.date(2020,1,1),datetime.date(2020,9,1)) for x in range(5*n)]sales_amt = [random.randint(0,1000) for x in range(5*n)]transactionDf = pd.DataFrame({"Item":transaction_items,"TransactionDt":transaction_dt,"Sales":sales_amt})return offerDf,transactionDf
offerDf,transactionDf = generate_data(n=100000)

You don’t need to worry about the random data generation code above. Just know how our random data looks like:

您无需担心上面的随机数据生成代码。 只要知道我们的随机数据是什么样子:

Once we have the data, we can do the non-equi join by merging the data on the column item and then filtering by the required condition.

有了数据后,我们可以通过合并列item上的数据,然后按所需条件进行过滤来进行非等价联接。

merged_df = pd.merge(offerDf,transactionDf,on='Item')pandas_solution = merged_df[(merged_df['TransactionDt']>=merged_df['StartDt']) &           (merged_df['TransactionDt']<=merged_df['EndDt'])]

The result is below just as we wanted:

结果如下所示:

PandaSQL解决方案 (The PandaSQL solution)

The Pandas solution is alright, and it does what we want, but we could also have used PandaSQL to get the same thing done in a much more readable way.

Pandas解决方案还可以,它可以满足我们的要求,但是我们也可以使用PandaSQL以更易读的方式完成同样的事情。

What is PandaSQL?

什么是PandaSQL ?

PandaSQL provides us with a way to write SQL on Pandas Dataframes. So if you have got some SQL queries already written, it might make more sense to use pandaSQL rather than converting them to pandas syntax. To get started with PandaSQL we install it simply with:

PandaSQL为我们提供了一种在Pandas Dataframe上编写SQL的方法。 因此,如果您已经编写了一些SQL查询,则使用pandaSQL而不是将其转换为pandas语法可能更有意义。 要开始使用PandaSQL,我们只需使用以下命令进行安装:

pip install -U pandasql

Once we have pandaSQL installed, we can use it by creating a pysqldf function that takes a query as an input and runs the query to return a Pandas DF. Don’t worry about the syntax; it remains more or less constant.

一旦安装了pandaSQL,就可以通过创建pysqldf函数来使用它,该函数将查询作为输入并运行查询以返回Pandas DF。 不用担心语法。 它或多或少保持不变。

from pandasql import sqldfpysqldf = lambda q: sqldf(q, globals())

We can now run any SQL query on our Pandas data frames using this function. And, below is the non-equi join, we want to do in the much more readable SQL format.

现在,我们可以使用此函数在Pandas数据帧上运行任何SQL查询。 而且,下面是非等号联接,我们希望以更具可读性SQL格式进行操作。

q = """    SELECT A.*,B.TransactionDt,B.Sales        FROM            offerDf A        INNER JOIN            transactionDf B        ON             A.Item = B.Item AND            A.StartDt <= B.TransactionDt AND            A.EndDt >= B.TransactionDt;    """pandaSQL_solution = pysqldf(q)

The result is a pandas Dataframe as we would expect. The index is already reset for us, unlike before.

结果就是我们期望的熊猫数据框。 与以前不同,该索引已为我们重置。

注意事项: (Caveats:)

While the PandaSQL function lets us run SQL queries on our Pandas data frames and is an excellent tool to be aware of in certain situations, it is not as performant as pure pandas syntax.

虽然PandaSQL函数使我们可以在Pandas数据帧上运行SQL查询,并且是在某些情况下要注意的出色工具,但它的性能不如纯Pandas语法高。

When we time Pandas against the more readable PandaSQL, we find that the PandaSQL takes around 10x the time of native Pandas.

当我们将Pandas与更具可读性的PandaSQL进行计时时,我们发现PandaSQL花费的时间是本地Pandas的10倍左右。

结论 (Conclusion)

In this post of the Python Shorts series, we learned about pandaSQL, which lets us use SQL queries on our Dataframes. We also looked at how to do non-equi joins using both native pandas as well as pandaSQL.

在Python Shorts系列的这篇文章中,我们了解了pandaSQL,它使我们可以在数据框上使用SQL查询。 我们还研究了如何使用本地pandas和pandaSQL进行非等额联接。

While the PandaSQL library is not as performant as native pandas, it is a great addition to our data analytics toolbox when we want to do ad-hoc analysis and to people who feel much more comfortable with using SQL queries.

虽然PandaSQL库的性能不如本地熊猫,但它是我们想要进行即席分析的数据分析工具箱的一个很好的补充,对于那些更愿意使用SQL查询的人来说,它是一个很好的补充。

For a closer look at the code for this post, please visit my GitHub repository, where you can find the code for this post as well as all my posts.

要进一步了解该文章的代码,请访问我的GitHub存储库,在这里您可以找到该文章的代码以及我的所有文章。

继续学习 (Continue Learning)

If you want to learn more about Python 3, I would like to call out an excellent course on Learn Intermediate level Python from the University of Michigan. Do check it out.

如果您想了解有关Python 3的更多信息,我想在密歇根大学(University of Michigan)开设一门优秀的学习中级Python的课程。 请检查一下。

I am going to be writing more beginner-friendly posts in the future too. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz.

我将来也会写更多对初学者友好的文章。 在Medium上关注我,或订阅我的博客以了解有关它们的信息。 与往常一样,我欢迎您提供反馈和建设性的批评,可以在Twitter @mlwhiz上与我们联系 。

Also, a small disclaimer — There might be some affiliate links in this post to relevant resources, as sharing knowledge is never a bad idea.

另外,这是一个小的免责声明-由于共享知识从来都不是一个坏主意,因此本文中可能会有一些与相关资源相关的会员链接。

翻译自: https://towardsdatascience.com/when-pandas-is-not-enough-use-pandasql-d762b9b84b38

用python画熊猫


http://www.taodudu.cc/news/show-5813872.html

相关文章:

  • java画熊猫_Java-基础练习2
  • 少儿学编程系列---使用python turtle画熊猫
  • 3分钟,教你画三种软软萌萌的小熊猫~超详细教程,看完即可上手哦~
  • 给王者荣耀做一个各种信息的归纳
  • 学习【全栈之巅】Node.js + Vue.js 全栈开发王者荣耀手机端官网和管理后台笔记(2.10-2.12)
  • 我昏迷了!被王者荣耀的AI吊打后,队友想了一个损招……
  • deepin允许root登录_王者荣耀安全改战区免root
  • 王者荣耀服务器什么时候维护好19赛季,王者荣耀:S19新赛季开启时间确定,国服战力排名会提前锁定...
  • Java程序员开发5年,该如何制定自己的职业规划
  • 华为手机显示高德位置服务器,华为手机用户尝鲜!高德地图上线车道级导航:高精度还原真实道路场景...
  • js 跳转到指定位置 高德地图_在H5页面内通过地址调起高德地图实现导航
  • 高端地图导航代码android,ReactNative 调用手机地图(高德、百度)导航 Android(示例代码)...
  • 高德导航插件
  • 安卓开发,高德地图5.0版本导航部分手机出现白屏
  • Android声音管理AudioManager使用
  • android控制手机系统声音
  • Android 获取手机系统的声音设置管理通知提醒的声音
  • Android手机音量设置相关
  • 安卓声音管理器AudioManager的使用
  • Android之声音管理器《AudioManager》的使用以及音量控制
  • 根据学员英文名找到学员对象
  • 再见!验证码
  • 验证码的前世今生
  • dau计算公式_dau mau_mau dau计算公式_ndau是指
  • mx3 android6,魅族Flyme6全面推送!网友升级后傻了:竟还是安卓5.1
  • android o 小米 新功能6,Android O的新特性,原来魅族Flyme6早已实现
  • flyme android n,杨颜深夜回应 Flyme 6升级安卓N有定论
  • android 魅族手机bug多,魅族Flyme6是悟空请来的?Bug竟然有这么多?
  • flyme6 android 版本,魅族flyme6稳定版正式推送:Flyme6最好用的安卓系统,体验100分,看文说话!...
  • 王自如评价鸿蒙OS,王自如上手评测坚果Pro 2:来听听大神怎么说!

用python画熊猫_当熊猫不够用熊猫相关推荐

  1. python 画云图_【词云图】如何用python的第三方库jieba和wordcloud画词云图

    一直想学一下如何用python画词云图,觉得很好玩,本文就写一下我自己的一些尝试. 1.提前准备 一般准备以下四样就可以啦. 第一,电脑安装python,我装的是3.6. 第二,安装第三方库jieba ...

  2. 怎么用python画花瓣_怎么用python画花朵

    怎么用python画花朵?下面给大家讲解一下具体步骤: 第一步,打开菜单栏,输入idle,打开shell. 第二步,新建一个文件,并命名. 第三步,导入turtle模块,创建一个新窗口用于绘图,再创建 ...

  3. 知道经纬度用python画路线图_神级程序员教你用Python如何画一个中国地图!(好好玩)...

    为什么是Python 先来聊聊为什么做数据分析一定要用 Python 或 R 语言.编程语言这么多种, Java , PHP 都很成熟,但是为什么在最近热火的数据分析领域,很多人选择用 Python ...

  4. 用python画风车_用Python画小女孩放风筝的示例

    我就废话不多说了,直接上代码吧! # coding:utf-8 2import turtle as t 3import random 4# 画心 5def xin(): 6 def curvemove ...

  5. 如何用python画椭圆_怎么用python画椭圆?

    使用python画椭圆的方法: 首先使用两行代码引入Matplotlib扩展包:import matplotlib.pyplot as plt from matplotlib.patches impo ...

  6. 用python画圆锥_用python画一幅美瞳,今日份来自程序员的浪漫

    如果说,眼睛是心灵的窗户,那么,美瞳就是心灵的彩窗,就像下图中这样. 而我们今天所要挑战的,就是用python画美瞳,而且是五分钟之内画三百副争奇斗艳.各领风骚.绝不重样的美瞳.作为这颗地球上最纯情的 ...

  7. 怎么用python画房子_用python画一个小房子

    用python画一个小房子 2020年07月22日 | 萬仟网IT编程 | 我要评论 如何用python画一个小房子?效果图如下:代码如下:import turtle# 前置p = turtle.Pe ...

  8. 用python画皇冠_【推荐】手把手教你如何用Python画一棵漂亮樱花树含源码

    最近给大家整理了一下,挑了一些我觉得不错的代码分享给大家手把手教你如何用Python画一棵漂亮樱花树含源码. 动态生成樱花 效果图(这个是动态的): import turtle as T import ...

  9. python turtle画房子代码里面的窗子,如何用python画房子_用python画一个小房子

    如何用python画一个小房子? 效果图如下: 代码如下: import turtle # 前置 p = turtle.Pen() # 作者要说的话 for i in range(6): print( ...

  10. 用python画佩奇_使用python画个小猪佩奇的示例代码

    基本原理 选好画板大小,设置好画笔颜色.粗细,定位好位置,依次画鼻子.头.耳朵.眼睛.腮.嘴.身体.手脚.尾巴,完事儿. 都知道,Turtle 是 Python 内置的一个比较有趣味的模块,俗称&qu ...

最新文章

  1. ML之MLiR:利用多元线性回归法,从大量数据(csv文件)中提取五个因变量(输入运输任务总里程数、运输次数、三种不同的车型,预测需要花费的小时数)来预测一个自变量
  2. android edittext email,Android上EditText上的电子邮件地址验证
  3. Oracle视图的作用与安全性
  4. CIPAddressCtrl类的使用(IP地址与CString的互相转化)
  5. java streamhandler_java中的Lamdba表达式和Stream
  6. 什么是C语言中的隐式函数声明?
  7. RabbitMq(十五)消息的追踪查看配置及查看方法
  8. .net core 文件流保存图片_如何将图片打包成PDF文件进行保存?
  9. mysql中数据定义和数据控制语言_MySQL的DDL数据定义语言和DCL数据控制语言
  10. mysql function 参数默认值_MySQL参数log_bin_trust_function_creators介绍
  11. java mina 大文件传输_mina 传输java对象
  12. sql复制表结构和数据_SQL复制表
  13. 演练Ext JS 4.2自定义主题
  14. 百度人脸识别之人脸注册AddUser
  15. 华为p10测试软件,华为p10内存测试软件
  16. 色彩心理学:为什么快餐店不适合等人?
  17. 如何给电脑安装双系统
  18. java判断麻将听牌,和牌看听:麻将听牌种类大全
  19. 基于物理的渲染PBR(二):挑战手写pbr和IBL环境光部分的见解
  20. 自己设计的一个首尾相接js轮播图

热门文章

  1. Javascript ES6中数组去重最简便的两种方法(大概)
  2. 大数据学习之Hbase面试题
  3. Web安全 学习日记1 - BurpSuite
  4. 腾达fh450虚拟服务器,腾达(Tenda)FH450路由器设置上网方法
  5. 日期问题(C语言实现)
  6. NLP--jieba(二)
  7. 在windows部署hadoopSpark和IDEA
  8. 如何成为一名卓越的数据科学家?
  9. 解决秒杀系统超卖问题的三种方案
  10. [转载]委托中介卖房子 房款还没拿到却“惹”上了官司