MySQL 如何使用Pandas SQL查询风格选择数据子集

MySQL 如何使用Pandas SQL查询风格选择数据子集

阅读更多:MySQL 教程

简介

在此文章中,我将向您展示如何使用 Pandas 进行类 SQL 过滤操作进行数据分析。大多数公司的数据都存储在需要使用 SQL 才能检索和操作的数据库中。例如,像 Oracle、IBM、Microsoft 这样的公司都有自己的数据库和相应的 SQL 实现。

数据科学家在其职业生涯的某个阶段都要处理 SQL,因为数据并不总是存储在 CSV 文件中。我个人更喜欢使用 Oracle,因为我所在公司的大部分数据都存储在 Oracle 中。

情境 – 1 假设我们有一个任务,需要找出满足以下条件的所有电影数据。

  • 电影的语言应为英语(en)或西班牙语(es)。
  • 电影的受欢迎程度应在 500 和 1000 之间。
  • 电影的状态必须为“已发布”。
  • 电影的投票数必须大于 5000。对于上述情境,相应的 SQL 语句如下所示。
SELECT
FROM WHERE
title AS movie_title
,original_language AS movie_language
,popularityAS movie_popularity
,statusAS movie_status
,vote_count AS movie_vote_count movies_data
original_languageIN ('en', 'es')

AND status=('Released')
AND popularitybetween 500 AND 1000
AND vote_count > 5000;

现在您已经看到了该需求的 SQL,让我们逐步使用 Pandas 来实现。我将向您展示两种方法。

方法 1:布尔值索引

1. 将 movies_data 数据集加载到 DataFrame 中。

import pandas as pd movies = pd.read_csv("https://raw.githubusercontent.com/sasankac/TestDataSet/master/movies_data.csv")

为每个条件分配一个变量。

languages = [ "en" , "es" ] condition_on_languages = movies . original_language . isin ( languages )
condition_on_status = movies . status == "Released"
condition_on_popularity = movies . popularity . between ( 500 , 1000 )
condition_on_votecount = movies . vote_count > 5000

3. 组合所有条件(布尔数组)。

final_conditions = ( condition_on_languages & condition_on_status & condition_on_popularity & condition_on_votecount )
columns = [ "title" , "original_language" , "status" , "popularity" , "vote_count" ]
# clubbing all together movies . loc [ final_conditions , columns ]
title original_language status popularity vote_count
95 Interstellar en Released 724.247784 10867
788Deadpool en Released 514.569956 10995

方法 2:.query() 方法。

.query() 方法是一种类 SQL where 语句风格的数据过滤方法。条件可以作为字符串传递给该方法,但是列名必须不包含任何空格。

如果列名中包含空格,请使用 Python 的 replace 函数将其替换为下划线。

根据我的经验,当应用于较大的 DataFrame 时,query() 方法比上一种方法更快。

import pandas as pd movies = pd . read_csv ( "https://raw.githubusercontent.com/sasankac/TestDataSet/master/movies_data.csv" )

4. 构建查询字符串并执行方法。

请注意,使用跨多行的三个引号括起的字符串时,.query方法不起作用。

final_conditions = (
"original_language in ['en','es']"
"and status == 'Released' "
"and popularity > 500 "
"and popularity < 1000"
"and vote_count > 5000"
) final_result = movies . query ( final_conditions )
final_result

此外,通常情况下,“in”子句中有多个要检查的值。因此,上述语法并不是理想的工作方式。使用“@”符号可以引用Python变量。

还可以以Python列表的形式编写值,并使用它们进行操作(@)。

movie_languages = [ 'en' , 'es' ]
final_conditions = (
"original_language in @movie_languages "
"and status == 'Released' "
"and popularity > 500 "
"and popularity < 1000"
"and vote_count > 5000" )
final_result = movies . query ( final_conditions )
final_result

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程