文章目錄
安裝jupyter
pip3 install jupyter
打開jupyter文檔
1: 在命令行輸入以下命令
jupyter notebook
2:完成之後,Jupyter Notebooks 就會在默認網絡瀏覽器打開,地址是:
http://localhost:8888/tree
新建python文件
鏈接數據庫
鏈接 Mysql
from sqlalchemy import create_engine
mysql_engine = create_engine('mysql+pymysql://mysql:root&@127.0.0.1:3306/test_db?charset=utf8mb4')
鏈接 Redis
import redis
redis_engine = redis.Redis(host='127.0.0.1', port=6381,db=0)
鏈接 MongoDB
from pymongo import MongoClient
mongo_client = MongoClient("mongodb://127.0.0.1:27017")
mongo_engine = mongo_client.test_mongo
查詢數據
# 導入 pandas
import pandas as pd
查詢 Mysql 數據庫
map 用法
# 利用map,將時間戳轉化爲時分秒
df['需要轉化的列'].map(調用的轉化函數)
舉例如下:
常用時間轉換方法
# 利用pandas自帶方法,將時間戳轉化爲具體時間以及日期(此處轉化爲北京時間)
# 時間戳轉化爲具體時間
pd.to_datetime(df['created_time'], unit='s') + pd.Timedelta(hours=8)
# 時間戳轉化爲日期
pd.to_datetime(df['created_time']).dt.floor('d')
舉例如下:
根據關聯列,合併兩個文檔
df1.merge(df2, how='left', left_on='df1_column', right_on='df2_column', sort=False, copy=False)
舉例如下:
分組數量統計
# 根據 class 統計學生數量
df.set_index(['name_x', 'class']).count(level='class') # 以學生姓名爲唯一識別
df.groupby(['class'], as_index=False).count() # 以 class 分組
其餘常用方法
# 文檔合併
# pd.concat([df1,df2,df3,df4,df5,df6])
# 根據 mobile 列,刪除重複數據
df = df.drop_duplicates('mobile')
# 取出 class =1 的數據
df[df['class']==1]
# 取出 class =1 且 學生姓名爲 李一 的數據
df[(df['class']==1) & (df['name_x']=='李一')]