pandas to sql

## pandas json 转sql直接存入mysql

import requests
import pandas as pd
from sqlalchemy import create_engine

yconnect = create_engine('mysql+pymysql://root:[email protected]:3306/video?charset=utf8')


if __name__ == '__main__':
    url = "http://app.video.baidu.com/app?word=北京&pn=1&rn=50&order=1"

    r = requests.get(url)
    data = r.json()["result"]
    df = pd.DataFrame(data)

    del df['nsclick_v']
    # 表名baidu,数据库名video, 如果表以存在追加数据
    pd.io.sql.to_sql(df, 'baidu', yconnect, schema='video', if_exists='append')

pandas to dict

python pandas to dict import pandas as pd import json b = [{'source': 'baidu', 'num': 61}, {'source': 'cctv', 'num': 14}, {'source': 'cntv', 'num': 3}, {'source': 'cntv', 'num': 1}, {'source': 'cntv', 'num': 1}] if __name__ == '__main__': df =pd.DataFrame(b) c = df["num"].groupby(df['source']).sum()[:5] gg = pd.DataFrame(c) pandas_to_dict = gg.to_dict() pandas_to_json = gg.to_json() x = {'baidu': 61, 'cctv': 14, 'cntv': 5} y = {"微信": 0, "微博": 0,"头条": 0} #合并两个字典 z = dict(x,**y) print(z) q= [] dd ={'微信': 40, '微博': 0, '头条': 156, 'baidu': 610, 'cntv': 10} for v in dd: q. [Read More]