pandas用法之資料結構型別

2021-10-12 09:37:12 字數 3292 閱讀 9660

import pandas as pd
匯入csv或者xlsx檔案

df = pd.read_csv(

'name.csv'

,header=0)

#header指定表頭

df = pd.read_excel(

'name.xlsx'

)#也可以指定表sheetname=1

pd.read_csv(

'name.csv'

,sep =

';', encoding =

'gbk'

, parse_dates =

['date'

],dayfirst =

true

,index_col =1)

#sep指定用;號來作為列分隔符,parse_dates將指定列解析為日期,

#dayfirst日的位置在前,index_col設定索引列

#如果處理的字串中包含中文,那麼最好要搞懂所用字元的編碼,是gbk/gb2312/gb18030,還是utf-8,否則容易出現亂碼

可以輸出為xlsx格式和csv格式

df_inner.to_excel(

'excel_to_python.xlsx'

, sheet_name=

'bluewhale_cc'

)df_inner.to_csv(

'excel_to_python.csv'

)

寫入csv:

with

open

('data.csv'

,'w'

,newline='')

as csvfile:

f_csv = csv.writer(csvfile)

f_csv.writerows(data)

pandas建立資料表

df = pd.dataframe(

,columns =

['id'

,'date'

,'city'

,'age'])

print

(df)

資料顯示如下 :

id       date         city     age

0 1 2013-01-02 beijing 23

1 2 2013-01-03 sh 44

2 3 2013-01-04 guangzhou 54

3 4 2013-01-05 shenzhen 32

4 5 2013-01-06 shanghai 34

5 6 2013-01-07 beijing 32

s = pd.series(

[101

,102

,103

,104])

#用series建立乙個帶索引的dataframe

print

(s)

缺省會建立整型索引,資料顯示如下 :

0    101

1 102

2 103

3 104

dtype: int64

在運算元據之前,先來了解一下pd.dataframe的資料結構:

dates = pd.date_range(

'20201219'

,periods =3)

#建立時間序列

print

(dates)

'''datetimeindex(['2020-12-19', '2020-12-20', '2020-12-21'],

dtype='datetime64[ns]', freq='d')'''

col =

list

('abcdef'

)#等於['a', 'b', 'c', 'd'...]

df = pd.dataframe([[

1,2,

3,4,

5,6]

,['beijing '

,'sh'

,' guangzhou '

,'shenzhen'

,'shanghai'

,'beijing '],

[23,44

,54,32

,34,32

]],index = dates, columns = col)

結果為:

a   b            c         d         e         f

2020-12-19 1 2 3 4 5 6

2020-12-20 beijing sh guangzhou shenzhen shanghai beijing

2020-12-21 23 44 54 32 34 32

index是行索引,columns為列頭,values為資料值

開啟檔案csv,會自動建立index

也可以指定列為索引列:

df.reset_index(

)#重設索引

df.set_index(

'date'

)#設定日期為索引

檢視資料表資訊

df.head(

)#預設前5行資料

df.tail(

)#預設後5行資料

df.index #索引

df.values #資料表的值

df.columns #所有列名

df.shape #檢視資料維度

df.info(

)#資料表基本資訊

df.dtypes #每一列資料型別

df['列名'

].dtype #某一列的格式

df.isnull(

)#檢視空值,

df['列名'

].unique(

)#檢視該列唯一值

df.describe(

)#全部資料的快速統計彙總

pandas資料結構之Series

series 是一種類似於一維陣列的物件,它由一組資料和一組與之相關的資料標籤 lable 或者說索引 index 組成。現在我們使用series生成乙個最簡單的series物件,因為沒有給series指定索引,所以此時會使用預設索引 從0到n 1 from pandas import series...

Pandas資料結構之Series

import pandas as pd series類 生成series類的方法 1.obj pd.series 4,7,5,3 obj2 pd.series 4,7,5,3 index a b c d print obj2.values,obj2.index print obj2 a print ...

pandas資料結構之Dataframe

綜述 numpy主要用於進行運算 dataframe更切合於業務邏輯 dataframe的常用的屬性 屬性 說明 shape dataframe的形狀 values dataframe的值,numpy.ndarray index 行索引 index.name 行索引的名字 columns 列索引 c...