IPythonNotebook上CSV文件的SQL语句

您所在的位置:网站首页 python读取csv某一列 IPythonNotebook上CSV文件的SQL语句

IPythonNotebook上CSV文件的SQL语句

2023-03-19 19:57| 来源: 网络整理| 查看: 265

我有一个tabledata.csv文件,并且一直使用它pandas.read_csv来读取或选择具有特定条件的特定列。

例如,我使用以下代码选择其中的所有“名称” session_id =1,这在datascientistworkbench的IPython Notebook上运行良好。

df = pandas.read_csv('/resources/data/findhelp/tabledata.csv') df['name'][df['session_id']==1]

我只是想知道在读取csv文件之后,是否有可能以某种方式“切换/读取”它为sql数据库。(我很确定我使用正确的术语没有很好地解释它,对此表示抱歉!)。但是我想要的是我确实想在IPython Notebook上使用SQL语句来选择具有特定条件的特定行。就像我可以使用类似的东西:

Select `name`, count(distinct `session_id`) from tabledata where `session_id` like "100.1%" group by `session_id` order by `session_id`

但是我想我确实需要找出一种方法来将csv文件更改为另一个版本,以便可以使用sql语句。多谢!

1> Sam..:

这是使用内置的sqlite3程序包对pandas和sql的快速入门。一般来说,您可以以一种或另一种方式在熊猫中执行所有SQL操作。但是数据库当然是有用的。您需要做的第一件事是将原始df存储在sql数据库中,以便您可以对其进行查询。下面列出了步骤。

import pandas as pd import sqlite3 #read the CSV df = pd.read_csv('/resources/data/findhelp/tabledata.csv') #connect to a database cOnn= sqlite3.connect("Any_Database_Name.db") #if the db does not exist, this creates a Any_Database_Name.db file in the current directory #store your table in the database: df.to_sql('Some_Table_Name', conn) #read a SQL Query out of your database and into a pandas dataframe sql_string = 'SELECT * FROM Some_Table_Name' df = pd.read_sql(sql_string, conn)


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3