再見Excel,你好Pandas!
數據的寫⼊:
寫⼊數據時,要注意不同的⽂件格式選⽤不同的⽅法,如寫⼊csv⽂件使⽤to_csv,寫⼊ excel時使⽤to_excel,并且要注意添加編碼⽅式,下面創建⼀個表:
- from pandas import Series,DataFrame
- # 使用字典創建
- index_list['001','002','003','004','005','006','007','008','009','010']
- name_list = ['李白','王昭君','諸葛亮','狄仁杰','孫尚香','妲己','周瑜','張飛','王昭君','大
- 喬']
- age_list=[25,28,27,25,30,29,25,32,28,26]
- salary_list=['10k','12.5k','20k','14k','12k','17k','18k','21k','22k','21.5k']
- marital_list = ['NO','NO','YES','YES','NO','NO','NO','YES','NO','YES']
- dic={
- '姓名': Series(data=name_list,index=index_list),
- '年齡': Series(data=age_list,index=index_list),
- '薪資': Series(data=salary_list,index=index_list),
- '婚姻狀況': Series(data=marital_list,index=index_list)
- }
- df=DataFrame(dic)
- # 寫入csv,path_or_buf為寫入文本文件
- df.to_csv(path_or_buf='./People_Information.csv',
- encoding='utf_8_sig',index=False)
- print('end')
這⾥調⽤to_csv⽅法 寫⼊數據,可以指定路徑,參數encoding是指定編碼⽅式,這樣遇到中⽂不易出現亂碼,參數index=False是為了去除掉⾏索引,不然⾏索引1,2,3,4等也會放到表⾥。
數據的讀取:
讀取數據時,不同的⽂件格式使⽤的⽅法也不⼀樣, 讀取csv使⽤read_csv,excel使⽤ read_excel,并且可以指定⽂件進⾏讀,另外⼀個Excel⽂件可以創建多個表,然后在不同的表中存儲不同數據,這種形式的⽂件很常⻅。但是要注意csv⽂件不存在多個sheet的問題。
- 如: import pandas as pd
- #sheet_name指定讀取⼯作鋪中的那個sheet(sheet名稱)
- sheet1 = pd.read_excel('./data/sheet.xlsx',sheet_name='sheet1')
- print(sheet1.head())
- sheet2 = pd.read_excel('./data/sheet.xlsx',sheet_name='sheet2')
- print(sheet2.head())
- 當csv或者excel中數據的第⼀⾏是⼀條臟數據,可以利⽤read_excel()中的header參數進
- ⾏選擇哪⼀⾏作為我們的列索引。如:
- import pandas as pd
- #這里將header設置為1(第一行是0),代表數據將從第2行開始讀取,第一行的數據會被
- 忽略
- people = pd.read_csv('./data/People1.csv',header = 1)
- print(people.head())
如果都不滿⾜的你的要求,可以將header設置為None,列索引值會使⽤默認的1、2、 3、4,之后在⾃⾏設置。
當指定了header的值,讀出來的數據就是從該⾏開始向下切⽚,該⾏以上的數據會被忽略。