Python數據分析之pandas讀取數據
1)CSV文件讀取:
語法格式:pandas.read_csv(文件路徑)CSV文件內容如下:
import pandas as pdfile_path = 'e:pandas_studytest.csv'content = pd.read_csv(file_path)content.head() # 默認返回前5行數據content.head(3) # 返回前3行數據content.shape # 返回一個元組(總行數,總列數),總行數不包括標題行content.index # 返回索引,是一個可迭代的對象<class ’pandas.core.indexes.range.RangeIndex’>content.column # 返回所有的列名 Index([’姓名’, ’年齡’, ’籍貫’], dtype=’object’)content.dtypes # 返回的是每列的數據類型姓名 object年齡 int64籍貫 objectdtype: object
2)CSV文件讀取:
語法格式:pandas.read_csv(文件路徑)CSV文件內容如下:
import pandas as pdfile_path = 'e:pandas_studytest2.txt'content = pd.read_csv(file_path,sep=’t’,header = None ,names= [’name’,’age’,’adress’])#參數說明:# header = None 表示沒有標題行# sep=’t’ 表示去除分割符中的空格# names= [’name’,’age’,’adress’] ,列名依次自定義為’name’,’age’,’adress’content.head() # 默認返回前5行數據content.head(3) # 返回前3行數據content.shape # 返回一個元組(總行數,總列數),總行數不包括標題行content.index # 返回索引,是一個可迭代的對象<class ’pandas.core.indexes.range.RangeIndex’>content.column # 返回所有的列名 Index([’姓名’, ’年齡’, ’籍貫’], dtype=’object’)content.dtypes # 返回的是每列的數據類型三、excel文件讀取
import pandas as pdfile_path = 'e:pandas_studytest3.xlsx'content = pd.read_excel(file_path)content.head() # 默認返回前5行數據content.head(3) # 返回前3行數據content.shape # 返回一個元組(總行數,總列數),總行數不包括標題行content.index # 返回索引,是一個可迭代的對象<class ’pandas.core.indexes.range.RangeIndex’>content.column # 返回所有的列名 Index([’姓名’, ’年齡’, ’籍貫’], dtype=’object’)content.dtypes # 返回的是每列的數據類型姓名 object年齡 int64籍貫 objectdtype: object四、數據庫表格讀取
語法: pandas.read_sql(sql語句,數據庫連接對象)數據對象的創建,可以根據pymysql,cx_oracle等模塊連接mysql或者oracle。
到此這篇關于Python數據分析之pandas讀取數據的文章就介紹到這了,更多相關pandas讀取數據內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: