Python資料分析庫pandas ------ DataFrame

來源:互聯網
上載者:User

標籤:price   參數   1.2   python   元素   類型   操作   .data   class   

DataFrame的定義

 1 data = { 2     ‘color‘: [‘blue‘, ‘green‘, ‘yellow‘, ‘red‘, ‘white‘], 3     ‘object‘: [‘ball‘, ‘pen‘, ‘pecil‘, ‘paper‘, ‘mug‘], 4     ‘price‘: [1.2, 1, 2.3, 5, 6] 5 } 6 frame0 = pd.DataFrame(data) 7 print(frame0) 8 frame1 = pd.DataFrame(data, columns=[‘object‘, ‘price‘]) 9 print(frame1)10 frame2 = pd.DataFrame(data, index=[‘張三‘,‘李斯‘,‘王五‘,‘陳久‘,‘小明‘])11 print(frame2)12 Out[1]:13     color object  price14 0    blue   ball    1.215 1   green    pen    1.016 2  yellow  pecil    2.317 3     red  paper    5.018 4   white    mug    6.019   object  price20 0   ball    1.221 1    pen    1.022 2  pecil    2.323 3  paper    5.024 4    mug    6.025      color object  price26 張三    blue   ball    1.227 李斯   green    pen    1.028 王五  yellow  pecil    2.329 陳久     red  paper    5.030 小明   white    mug    6.0

  使用index參數可以設定index資訊

 

選取元素

 1 print(frame1.columns) 2 print(frame2.index) 3 print(frame2[‘price‘]) 4 print(frame2.price) 5 Out[2]: 6 Index([‘object‘, ‘price‘], dtype=‘object‘) 7 Index([‘張三‘, ‘李斯‘, ‘王五‘, ‘陳久‘, ‘小明‘], dtype=‘object‘) 8 張三    1.2 9 李斯    1.010 王五    2.311 陳久    5.012 小明    6.013 Name: price, dtype: float6414 張三    1.215 李斯    1.016 王五    2.317 陳久    5.018 小明    6.019 Name: price, dtype: float64

  一般我們常需要按列取值,那麼DataFrame提供了 lociloc 供大家選擇,但是兩者之間是由區別的。

 1 print(frame2) 2 print(frame2.loc[‘王五‘])  # loc可以使用字串類型的index,而iloc只能是int型的 3 print(frame0.iloc[2]) 4 Out[2]: 5      color object  price 6 張三    blue   ball    1.2 7 李斯   green    pen    1.0 8 王五  yellow  pecil    2.3 9 陳久     red  paper    5.010 小明   white    mug    6.011 color     yellow12 object     pecil13 price        2.314 Name: 王五, dtype: object15 color     yellow16 object     pecil17 price        2.318 Name: 2, dtype: object

  一般取值操作

 1 print(frame2[2:3])  # 取行 2 print(frame0[‘object‘])  # 取列 3 print(frame0[‘object‘][1:3])  # 取列的元素 4 print(frame0.iloc[0:4, 1:3])  # 取一塊的元素       ******************************************************************** 5 Out[3]: 6      color object  price 7 王五  yellow  pecil    2.3 8 0     ball 9 1      pen10 2    pecil11 3    paper12 4      mug13 Name: object, dtype: object14 1      pen15 2    pecil16 Name: object, dtype: object17   object  price18 0   ball    1.219 1    pen    1.020 2  pecil    2.321 3  paper    5.0

 

Python資料分析庫pandas ------ DataFrame

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.