国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python中pandas.DataFrame的簡單操作方法(創建、索引、增添與刪除)

2020-02-23 04:25:14
字體:
來源:轉載
供稿:網友

前言

最近在網上搜了許多關于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            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 内黄县| 蒙自县| 安塞县| 包头市| 长沙市| 赤水市| 响水县| 兴山县| 邵东县| 安福县| 公安县| 林西县| 通山县| 玛多县| 宜章县| 城市| 嫩江县| 乐陵市| 聂拉木县| 海林市| 文昌市| 江津市| 噶尔县| 子洲县| 岗巴县| 炉霍县| 周口市| 宜章县| 彩票| 会同县| 扬中市| 东乡族自治县| 桑植县| 全州县| 靖边县| 筠连县| 临漳县| 科技| 周至县| 镇安县| 封丘县|