Python data analysis read file read CSV read Excel read MySQL read MongoDB

Python data analysis read file read CSV read Excel read MySQL read MongoDB

For data analysis in Python, most of the tutorials are about numpy, then about Dataframe, and then about reading files. But when I was reading the book, the first two chapters were really dizzy, so let's start our Python data analysis by reading the file.

Read CSV

  • Read csv to read through read_csv
import pandas as pd
zhuanti = pd.read_csv(open('C:/Users/luopan/Desktop/xiaozhu.csv', encoding='utf-8'))
zhuanti
  • Set the first column as an index
import pandas as pd
zhuanti1 = pd.read_csv(open('C:/Users/luopan/Desktop/xiaozhu.csv', encoding='utf-8'), index_col=0)
zhuanti1
  • Set the header, remove the header here
import pandas as pd
zhuanti2 = pd.read_csv(open('C:/Users/luopan/Desktop/xiaozhu.csv', encoding='utf-8'),index_col=0,header=None)
zhuanti2
  • Skip the first 2 lines
import pandas as pd
zhuanti3 = pd.read_csv(open('C:/Users/luopan/Desktop/xiaozhu.csv',encoding='utf-8'),skiprows=[1,2],index_col=0)
zhuanti3

Read Excel

  • Use read_excel to read excel files
import pandas as pd
test = pd.read_excel('C:/Users/luopan/Desktop/test.xlsx',sheetname='Sheet2',header=None)
test

Read MySQL

import pandas as pd
import pymysql
conn = pymysql.connect(host='localhost', user='root', passwd='123456', db='test', port=3306, charset='utf8')
jianshu = pd.read_sql('select * from jianshu1',conn)
jianshu

Read MongoDB

import pandas as pd
import pymongo
client = pymongo.MongoClient('localhost',port = 27017)
test = client['test']
tieba = test['tieba']
data = pd.DataFrame(list(tieba.find()))
data
Reference: https://cloud.tencent.com/developer/article/1155610 Python Data Analysis Read File Read CSV Read Excel Read MySQL Read MongoDB-Cloud + Community-Tencent Cloud