pandas 讀取本地csv檔案,處理,儲存
阿新 • • 發佈:2018-12-15
from sqlalchemy import create_engine import pandas as pd from pandas import DataFrame, Series engine = create_engine(“mysql+pymysql://root:[email protected]:3306/tables”, encoding=‘utf8’, echo=True)
解析csv檔案中, name這一列,就資料中的\d+.替換
def excel_to_mysql(): excel = pd.read_csv("tea.csv") mm_list = [] for m in excel['name'].dropna(): mm = re.sub(r"\d+.","" ,m) mm_list.append(mm) excel['name'] = pd.Series(mm_list) print(excel) excel.to_csv('a.csv') # excel.to_sql(name='tabalename',con=engine, if_exists='append',index=False)
同樣功能優化如下
def excel_to_mysql():
excel = pd.read_csv("tea.csv")
excel['name'] = excel.name.apply(lambda ele: re.sub(r"\d+.", "", ele))
print(excel)
excel.to_csv('a.csv')