数据挖掘工具pandas(十三)对csv、excel、mysql读取和存储

一,pd对于csv文件的读取和存储

1,pd读取csv文件
df_xml = pd.read_csv("./outputs/"+table+".csv", engine='python', 
encoding='utf_8_sig')
2,pd存储csv文件
df.to_csv("./outputs/df_xml.csv", index=False, mode='w', header=True,
 encoding='utf_8_sig')

二,pd对于excel文件的读取和存储

1,pd读取excel文件

https://www.jb51.net/article/156414.htm
https://blog.csdn.net/weixin_38546295/article/details/83537558

data = pd.read_excel(path)
2,pd存储excel文件
import xlwt

df.to_excel("./outputs/"+table+".xls", index=False, header=True,
 encoding='utf_8_sig')

三,pd对于mysql数据的读取和存储

1,pd读取mysql数据
1) 第一种方法,pd.read_sql
import pymysql

db = pymysql.connect(
    host="172.31.0.54",
    port=3307,
    user="root",
    passwd="ssb@2017",
    db="ssb_ibt",
    charset="utf8"
)
sql = "select * from table_name where ctid=214;"
df=pd.read_sql(sql, db , index_col=None, coerce_float=False, params=None, parse_dates=None, columns=None, chunksize=None)

https://blog.csdn.net/The_Time_Runner/article/details/86601988
sql:SQL命令字符串
con:连接sql数据库的engine,一般可以用SQLalchemy或者pymysql之类的包建立
index_col: 选择某一列作为index
coerce_float:非常有用,将数字形式的字符串直接以float型读入
parse_dates:将某一列日期型字符串转换为datetime型数据,与pd.to_datetime函数功能类似。可以直接提供需要转换的列名以默认的日期形式转换,也可以用字典的格式提供列名和转换的日期格式,比如{column_name: format string}(format string:"%Y:%m:%H:%M:%S")。
columns:要选取的列。一般没啥用,因为在sql命令里面一般就指定要选择的列了
chunksize:如果提供了一个整数值,那么就会返回一个generator,每次输出的行数就是提供的值的大小。

2)第二种方法,pd.read_sql_table
import sqlalchemy as sqla

engine = sqla.create_engine("mysql+pymysql://" + "root" + ':' + "123456" + '@' + "127.0.0.1" + ":" + "3306" + '/' + "word" + '?charset=utf8')
df = pd.read_sql_table('ssb_editor_category_template_item', engine, columns=['id',"logic_id"])
print(df.head())

columns:选择的字段

3)第三种方法,pd.read_sql_query
import sqlalchemy as sqla

engine = sqla.create_engine("mysql+pymysql://" + "root" + ':' + "123456" + '@' + "127.0.0.1" + ":" + "3306" + '/' + "word" + '?charset=utf8')
query = "select * from "+ 'ssb_editor_category_template_item'+ " where ctid = " + ctid +";"
df = pd.read_sql_query(query, engine)
print(df.head())
2,pd储存mysql数据
1) 第一种方法,pymysql(可回滚)
import pymysql

db = pymysql.connect(
    host="172.31.0.54",
    port=3307,
    user="root",
    passwd="ssb@2017",
    db="ssb_ibt",
    charset="utf8"
)
try:
    cursor = db.cursor()
    with open(csv_path, 'r', encoding='utf8') as csv_file:
        reader = csv.reader(csv_file)
        head = next(reader)
        # print(head)
        for row in reader:
            args = tuple(row[:])
            cursor.execute(sql, args)
                
    cursor.close()  # 先关闭游标
    db.commit()
except Exception as e:
    print(e)
    db.rollback()
2)第二种方法,sqlalchemy
import sqlalchemy as sqla	

engine = sqla.create_engine("mysql+pymysql://" + "root" + ':' + "123456" + '@' + "127.0.0.1" + ":" + "3306" + '/' + "word" + '?charset=utf8')
df.to_sql("ssb_editor_category_template_item",engine,index=False, if_exists='append')

四,解决报错

1,Warning: (1366, "Incorrect string value: ‘\xD6\xD0\xB9\xFA\xB1\xEA…’ for column 'VARIABLE_VA

https://www.cnblogs.com/shiqi17/p/9409228.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章