前言
最近在網上搜了許多關于pandas.DataFrame的操作說明,都是一些基礎的操作,但是這些操作組合起來還是比較費時間去正確操作DataFrame,花了我挺長時間去調整BUG的。我在這里做一些總結,方便你我他。感興趣的朋友們一起來看看吧。
一、創建DataFrame的簡單操作:
1、根據字典創造:
In [1]: import pandas as pdIn [3]: aa={'one':[1,2,3],'two':[2,3,4],'three':[3,4,5]}In [4]: bb=pd.DataFrame(aa)In [5]: bbOut[5]: one three two0 1 3 21 2 4 32 3 5 4`字典中的keys就是DataFrame里面的columns,但是沒有index的值,所以需要自己設定,不設定默認是從零開始計數。
bb=pd.DataFrame(aa,index=['first','second','third'])bbOut[7]: one three twofirst 1 3 2second 2 4 3third 3 5 4
2、從多維數組中創建
import numpy as npIn [9]: del aaIn [10]: aa=np.array([[1,2,3],[4,5,6],[7,8,9]])In [11]: aaOut[11]: array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])In [12]: bb=pd.DataFrame(aa)In [13]: bbOut[13]: 0 1 20 1 2 31 4 5 62 7 8 9
從多維數組中創建就需要為DataFrame賦值columns和index,否則就是默認的,很丑的。
bb=pd.DataFrame(aa,index=[22,33,44],columns=['one','two','three'])In [15]: bbOut[15]: one two three22 1 2 333 4 5 644 7 8 9
3、用其他的DataFrame創建
bb=pd.DataFrame(aa,index=[22,33,44],columns=['one','two','three'])bbOut[15]: one two three22 1 2 333 4 5 644 7 8 9cc=bb[['one','three']].copy()CcOut[17]: one three22 1 333 4 644 7 9
這里的拷貝是深拷貝,改變cc中的值并不能改變bb中的值。
cc['three'][22]=5bbOut[19]: one two three22 1 2 333 4 5 644 7 8 9ccOut[20]: one three22 1 533 4 644 7 9
二、DataFrame的索引操作:
對于一個DataFrame來說,索引是最煩的,最易出錯的。
1、索引一列或幾列,比較簡單:
bb['one']Out[21]: 22 133 444 7Name: one, dtype: int32
多個列名需要將輸入的列名存在一個列表里,才是個collerable的變量,否則會報錯。
bb[['one','three']]Out[29]: one three22 1 333 4 644 7 9
2、索引一條記錄或幾條記錄:
bb[1:3]Out[27]: one two three33 4 5 644 7 8 9bb[:1]Out[28]: one two three22 1 2 3
這里注意冒號是必須有的,否則是索引列的了。
3、索引某幾列的變量的某幾條記錄,這個折磨了我好久:
第一種
bb.loc[[22,33]][['one','three']]Out[30]: one three22 1 333 4 6
這種不能改變這里面的值,你只是能讀值,不能寫值,可能和loc()函數有關:
bb.loc[[22,33]][['one','three']]=[[2,2],[3,6]]In [32]: bbOut[32]: one two three22 1 2 333 4 5 644 7 8 9
新聞熱點
疑難解答