1. 程式人生 > >pandas建立資料表及資料讀寫

pandas建立資料表及資料讀寫

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f', 'h'],
                  columns=['one', 'two', 'three'])#建立一個數據表格
df['four'] = 'bar'#加入新的一列
df['five'] = df['one'] > 0#加入新的一列,通過判斷資料大小加入bool型列
df['six'] = 'ball'

df

onetwothreefourfivesix
a-0.7897190.8217450.441262barFalseball
c-0.305278-2.4248531.876305barFalseball
e1.009320-0.820649-0.022101barTrueball
f0.490864-0.196651-1.365382barTrueball
h-1.342600-0.0543220.196686barFalseball

df2 = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])#增加新的行並填充為NaN

df2

onetwothreefourfivesix
a0.9494880.851231-0.654962barTrueball
bNaNNaNNaNNaNNaNNaN
c0.785113-0.640581-0.532271barTrueball
dNaNNaNNaNNaNNaNNaN
e-0.2311921.7404890.421804barFalseball
f-0.4741950.2555730.057918barFalseball
gNaNNaNNaNNaNNaNNaN
h1.3406230.793281-0.114751barTrueball
df2['one']=df2['one'].fillna(0)#按列填充

df2

onetwothreefourfivesix
a0.9494880.851231-0.654962barTrueball
b0.000000NaNNaNNaNNaNNaN
c0.785113-0.640581-0.532271barTrueball
d0.000000NaNNaNNaNNaNNaN
e-0.2311921.7404890.421804barFalseball
f-0.4741950.2555730.057918barFalseball
g0.000000NaNNaNNaNNaNNaN
h1.3406230.793281-0.114751barTrueball

讀取Excel資料

#讀取excel資料
import pandas as pd
FileReadPath = r"D:\AI\Others\test.xlsx"
df = pd.read_excel(FileReadPath)
df.head()

寫Excel資料

#把資料寫入Excel
import pandas as pd
data = {'country':['aaa','btb','ccc'],  
       'population':[10,12,14]}  
df = pd.DataFrame(data)#構建DataFrame結構  
FileWritePath = r"D:\AI\Others\test1.xlsx"
writer = pd.ExcelWriter(FileWritePath)
df.to_excel(writer,'Sheet1')
writer.save()