- 列表,序列(pandas.Series), numpy.ndarray的字典
- 二維numpy.ndarray
- 別的DataFrame
- 結構化的記錄(structured arrays)
其中,我最喜歡的是通過二維ndarray創建DataFrame,因爲代碼敲得最少:
1
2
3
4
5
6
7
8
|
import
pandas as pd import
numpy as np df =
pd.DataFrame(np.random.randn( 3 ,
4 )) df 0
1 2 3 0
0.236175 - 0.394792
- 0.171866
0.304012 1
0.651926 0.989046
0.160389 0.482936 2
- 1.039824 0.401105
- 0.492714
- 1.220438 |
當然你還可以參考我的這篇文章從mysql數據庫或者csv文件中載入數據到dataframe。
dataframe中index用來標識行,column標識列,shape表示維度。
1
2
3
|
df.index
df.columns df.shape |
通過describe方法,我們可以對df中的數據有個大概的瞭解:
1
2
3
4
5
6
7
8
9
10
|
df.describe() 0
1 2 3 count 3.000000
3.000000 3.000000
3.000000 mean - 0.050574
0.331786 - 0.168064
- 0.144496 std 0.881574
0.694518 0.326568
0.936077 min
- 1.039824 - 0.394792
- 0.492714
- 1.220438 25 %
- 0.401824
0.003156 - 0.332290
- 0.458213 50 %
0.236175 0.401105
- 0.171866
0.304012 75 %
0.444051 0.695076
- 0.005739
0.393474 max
0.651926 0.989046
0.160389 0.482936 |
2. 數據select, del, update。
按照列名select:
1
2
3
4
5
|
df[ 0 ] 0
0.236175 1
0.651926 2
- 1.039824 |
按照行數select:
1
|
df[: 3 ]
#選取前3行 |
按照索引select:
1
2
3
4
5
6
|
df.loc[ 0 ] 0
0.236175 1
- 0.394792 2
- 0.171866 3
0.304012 |
按照行數和列數select:
1
2
3
4
5
|
df.iloc[ 3 ]
#選取第3行 df.iloc[ 2 : 4 ]
#選取第2到第3行 df.iloc[ 0 , 1 ]
#選取第0行1列的元素 dat.iloc[: 2 , : 3 ]
#選取第0行到第1行,第0列到第2列區域內的元素 df1.iloc[[ 1 , 3 , 5 ],[ 1 , 3 ]]
#選取第1,3,5行,第1,3列區域內的元素 |
刪除某列:
1
2
3
4
5
6
|
del
df[ 0 ] df 1
2 3 0
- 0.394792 - 0.171866
0.304012 1
0.989046 0.160389
0.482936 2
0.401105 - 0.492714
- 1.220438 |
刪除某行:
1
2
3
4
5
|
df.drop( 0 ) 1
2 3 1
0.989046 0.160389
0.482936 2
0.401105 - 0.492714
- 1.220438 |
3.運算。
基本運算:
1
2
3
4
5
6
|
df[ 4 ]
= df[ 1 ]
+ df[ 2 ] 1
2 3 4 0
- 0.394792 - 0.171866
0.304012 - 0.566659 1
0.989046 0.160389
0.482936 1.149435 2
0.401105 - 0.492714
- 1.220438
- 0.091609 |
map運算,和python中的map有些類似:
1
2
3
4
|
df[ 4 ]. map ( int ) 0
0 1
1 2
0 |
apply運算:
1
2
3
4
5
6
|
df. apply ( sum ) 1
0.995359 2
- 0.504192 3
- 0.433489 4
0.491167 |
4. Group by 操作。
pandas中的group by 操作是我的最愛,不用把數據導入excel或者mysql就可以進行靈活的group by 操作,簡化了分析過程。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
df[ 0 ]
= [ 'A' ,
'A' ,
'B' ] df 1
2 3 4
0 0
- 0.394792 - 0.171866
0.304012 - 0.566659
A 1
0.989046 0.160389
0.482936 1.149435
A 2
0.401105 - 0.492714
- 1.220438
- 0.091609 B g =
df.groupby([ 0 ]) g.size() A 2 B 1 g. sum () 1
2 3 4 0 A 0.594254
- 0.011478
0.786948 0.582776 B 0.401105
- 0.492714
- 1.220438 - 0.091609 |
groupby選擇列和迭代
g = df.groupby(df['artist_id'])gsize=g.size()
aa=g.sum()
5. 導出到csv文件
dataframe可以使用to_csv方法方便地導出到csv文件中,如果數據中含有中文,一般encoding指定爲”utf-8″,否則導出時程序會因爲不能識別相應的字符串而拋出異常,index指定爲False表示不用導出dataframe的index數據。
1
|
df.to_csv(file_path, encoding = 'utf-8' , index = False ) |