Pandas的DataFrame數據類型


縱軸表示不同索引axis=0,橫軸表示不同列axis=1

 

 DataFrame類型創建

1.從二維ndarray對象創建

 

 1 import pandas as pd
 2 
 3 import numpy as np
 4 
 5 d=pd.DataFrame(np.arange(10).reshape(2,5))
 6 
 7 d
 8 Out[4]: 
 9    0  1  2  3  4
10 0  0  1  2  3  4
11 1  5  6  7  8  9 #自動生成行索引和列索引

2.從一維ndarray對象字典創建

 1 import pandas as pd
 2 
 3 dt={'one':pd.Series([1,2,3],index=['a','b','c']),
 4 'two':pd.Series([8,7,6,5],index=['a','b','c','w'])}
 5 
 6 dt
 7 Out[9]: 
 8 {'one': a    1
 9  b    2
10  c    3
11  dtype: int64, 'two': a    8
12  b    7
13  c    6
14  w    5
15  dtype: int64}
16 
17 d=pd.DataFrame(dt)#原字典中的鍵變成列索引值,列索引位值中的Series數據中的索引並集 18 
19 d
20 Out[11]: 
21    one  two
22 a  1.0    8
23 b  2.0    7
24 c  3.0    6
25 w  NaN    5
26 
27 pd.DataFrame(dt,index=['a','b','c'],columns=['two','three'])
28 Out[13]: 
29    two three
30 a    8   NaN
31 b    7   NaN
32 c    6   NaN #缺少的元素會被自動補齊

3.從列表類型的字典創建

 1 import pandas as pd
 2 
 3 dl={'one':[1,2,3,4],'two':[3,5,6,9]}
 4 
 5 pd.DataFrame(dl,index=['a','b','c','d']) #這里注意后加的索引值得跟字典里的值數一樣  6 Out[28]: 
 7    one  two
 8 a    1    3
 9 b    2    5
10 c    3    6
11 d    4    9

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM