1.Series獲取值: s.values
DataFrame也存在values,返回的是二維ndarray數據
In [3]: s=pd.Series([4, 7, -5, 3])
...: s.values
Out[3]: array([ 4, 7, -5, 3], dtype=int64)
2.Series轉換為列表: list(s)
In [4]: list(s)
Out[4]: [4, 7, -5, 3]
3.Series索引: s[:]
In [5]: s=pd.Series([4, 7, -5, 3],index=list('adbs'))
...: s[1:]
Out[5]:
d 7
b -5
s 3
dtype: int64
In [6]: s[['a','s']]
Out[6]:
a 4
s 3
dtype: int64
4.Series數據篩選: s[s>i]
#篩選大于3的值
In [7]: s[s>3]
Out[7]:
a 4
d 7
dtype: int64
5.判斷Series是否存在某個索引或某個值: x in s
#是否存在索引值
In [8]: 'a' in s
Out[8]: True
#是否存在某個值
In [9]: 7 in s.values
Out[9]: True
In [10]: 10 in s.values
Out[10]: False
6.DataFrame更改列順序pd.DataFrame(data,columns=[])
- data可以是用于創建DataFrame的合適的數據,也可以是 DataFrame。
- 如果原數據存在列名,則根據新的columns順序調整列順序,如果不存在,則會引入NaN值。
- 還可以添加index對行索引進行更改。如果data不是DataFrame,則一般而言index的長度需和數據的行數相同,否則會創建失敗。
In [11]: data = {'省市': ['重慶', '重慶', '重慶', '成都', '成都', '成都'],
...: '年份': [2014, 2015, 2016, 2014, 2015, 2016],
...: '常住人口': [2991.0, 3107.0, 3048.0, 1465.8, 1591.8, 1604.5]}
...: df=pd.DataFrame(data)
In [12]: df
Out[12]:
省市 年份 常住人口
0 重慶 2014 2991.0
1 重慶 2015 3107.0
2 重慶 2016 3048.0
3 成都 2014 1465.8
4 成都 2015 1591.8
5 成都 2016 1604.5
#更改列順序
In [13]: pd.DataFrame(data,columns=['年份','常住人口','省市'])
Out[13]:
年份 常住人口 省市
0 2014 2991.0 重慶
1 2015 3107.0 重慶
2 2016 3048.0 重慶
3 2014 1465.8 成都
4 2015 1591.8 成都
5 2016 1604.5 成都
#當添加了未知列時,會引入NaN值。注意index添加的數量必須和原有行數一致,否則會報錯
In [14]: pd.DataFrame(data,columns=['年份','常住人口','省市','GDP'],
...: index=list('abcdef'))
Out[14]:
年份 常住人口 省市 GDP
a 2014 2991.0 重慶 NaN
b 2015 3107.0 重慶 NaN
c 2016 3048.0 重慶 NaN
d 2014 1465.8 成都 NaN
e 2015 1591.8 成都 NaN
f 2016 1604.5 成都 NaN
7.DataFrame的添加列: df['label']=data
即可通過此種方式添加任何列,如果data是列表,需注意其長度和df的長度一致。如果添加的是Series,則會通過索引(index)對齊數據,缺失數據將會被添加NaN值。
In [17]: df['GDP']=2000
In [18]: df
Out[18]:
省市 年份 常住人口 GDP
0 重慶 2014 2991.0 2000
1 重慶 2015 3107.0 2000
2 重慶 2016 3048.0 2000
3 成都 2014 1465.8 2000
4 成都 2015 1591.8 2000
5 成都 2016 1604.5 2000
8.DataFrame行列轉置(行列切換): df.T
In [19]: df.T
Out[19]:
0 1 2 3 4 5
省市 重慶 重慶 重慶 成都 成都 成都
年份 2014 2015 2016 2014 2015 2016
常住人口 2991 3107 3048 1465.8 1591.8 1604.5
GDP 2000 2000 2000 2000 2000 2000
9.DataFrame的刪除列: del df['label']
注意是原地刪除
In [3]: df
Out[3]:
常住人口 年份 省市
0 2991.0 2014 重慶
1 3107.0 2015 重慶
2 3048.0 2016 重慶
3 1465.8 2014 成都
4 1591.8 2015 成都
5 1604.5 2016 成都
In [4]: df['是否重慶']=df['省市']=='重慶'
In [5]: df
Out[5]:
常住人口 年份 省市 是否重慶
0 2991.0 2014 重慶 True
1 3107.0 2015 重慶 True
2 3048.0 2016 重慶 True
3 1465.8 2014 成都 False
4 1591.8 2015 成都 False
5 1604.5 2016 成都 False
In [6]: del df['是否重慶']
In [7]: df
Out[7]:
常住人口 年份 省市
0 2991.0 2014 重慶
1 3107.0 2015 重慶
2 3048.0 2016 重慶
3 1465.8 2014 成都
4 1591.8 2015 成都
5 1604.5 2016 成都
10.DataFrame的重新索引行: df.reindex([])
reindex傳入的index列表是什么就會按照index列表順序重新組織數據,如果新的index中有原df的索引沒有的值,則索引對應的行將會引入NaN值,可以使用fill_value=value對NaN值進行填充。
In [10]: df2=pd.DataFrame(np.arange(9).reshape((3, 3)),
...: index=['a', 'c', 'd'],
...: columns=['Ohio', 'Texas', 'California'])
In [11]: df2
Out[11]:
Ohio Texas California
a 0 1 2
c 3 4 5
d 6 7 8
In [12]: df2.reindex(['a', 'b', 'c', 'd'])
Out[12]:
Ohio Texas California
a 0.0 1.0 2.0
b NaN NaN NaN
c 3.0 4.0 5.0
d 6.0 7.0 8.0
In [13]: df2.reindex(['a','x','c'])
Out[13]:
Ohio Texas California
a 0.0 1.0 2.0
x NaN NaN NaN
c 3.0 4.0 5.0
11.DataFrame的重新索引列: df.reindex(columns=[])
In [14]: states = ['Texas', 'chongqing', 'California']
...: df2.reindex(columns=states)
Out[14]:
Texas chongqing California
a 1 NaN 2
c 4 NaN 5
d 7 NaN 8
12.DataFrame的更改行列索引(修改/重命名行列標題)方法1:df.rename(index={},columns={}),這里不會對原數據進行修改
如果要修改原數據,可以增加參數 inplace=True
和重新索引行列不同的是,我們可能希望對行列的索引進行重構,例如從某些系統導出的列標題數據可能是一些英文縮寫,而我們為了辨識希望將其替換為全稱以便大家理解。rename的index和columns參數分別對行和列的索引進行修改,傳入的數據類型為字典。如下例:
In [12]: df
Out[12]:
常住人口 年份 省市
0 2991.0 2014 重慶
1 3107.0 2015 重慶
2 3048.0 2016 重慶
3 1465.8 2014 成都
4 1591.8 2015 成都
5 1604.5 2016 成都
In [15]: idx=dict(zip(range(6),list('abcdef')))
In [16]: idx
Out[16]: {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f'}
In [17]: df.rename(index=idx)
Out[17]:
常住人口 年份 省市
a 2991.0 2014 重慶
b 3107.0 2015 重慶
c 3048.0 2016 重慶
d 1465.8 2014 成都
e 1591.8 2015 成都
f 1604.5 2016 成都
13.DataFrame的更改行列索引(修改/重命名行列標題)方法2: df.index=[],df.columns=[],這里會對原數據進行修改
注意:這里賦值的列表必須與index和columns的長度一致,因此重命名時應注意索引列表的順序。
In [18]: df
Out[18]:
常住人口 年份 省市
0 2991.0 2014 重慶
1 3107.0 2015 重慶
2 3048.0 2016 重慶
3 1465.8 2014 成都
4 1591.8 2015 成都
5 1604.5 2016 成都
In [19]: df.index=list('abcdef')
In [20]: df
Out[20]:
常住人口 年份 省市
a 2991.0 2014 重慶
b 3107.0 2015 重慶
c 3048.0 2016 重慶
d 1465.8 2014 成都
e 1591.8 2015 成都
f 1604.5 2016 成都
In [22]: df.columns=['a1','a2','a3']
In [23]: df
Out[23]:
a1 a2 a3
a 2991.0 2014 重慶
b 3107.0 2015 重慶
c 3048.0 2016 重慶
d 1465.8 2014 成都
e 1591.8 2015 成都
f 1604.5 2016 成都
14.DataFrame的索引方式-字典(標簽)或屬性索引: df['label'] df.label
In [15]: df.年份
Out[15]:
0 2014
1 2015
2 2016
3 2014
4 2015
5 2016
Name: 年份, dtype: int64
In [16]: df[['年份','省市']]
Out[16]:
年份 省市
0 2014 重慶
1 2015 重慶
2 2016 重慶
3 2014 成都
4 2015 成都
5 2016 成都
#通過切片選取行
In [18]: df[:2]
Out[18]:
常住人口 年份 省市
0 2991.0 2014 重慶
1 3107.0 2015 重慶
#通過布爾型數據選取
In [22]: df[df['年份']>2015]
Out[22]:
常住人口 年份 省市
2 3048.0 2016 重慶
5 1604.5 2016 成都
15.DataFrame的索引方式-loc和iloc:df.loc[],df.iloc[]
In [23]: data = {'省市': ['重慶', '重慶', '重慶', '成都', '成都', '成都'],
...: '年份': [2014, 2015, 2016, 2014, 2015, 2016],
...: '常住人口': [2991.0, 3107.0, 3048.0, 1465.8, 1591.8, 1604.5]}
...: df3=pd.DataFrame(data,index=list('abcdef'))
In [24]: df3
Out[24]:
常住人口 年份 省市
a 2991.0 2014 重慶
b 3107.0 2015 重慶
c 3048.0 2016 重慶
d 1465.8 2014 成都
e 1591.8 2015 成都
f 1604.5 2016 成都
#通過標簽選擇一行和多列
In [27]: df3.loc['a',['常住人口','省市']]
Out[27]:
常住人口 2991
省市 重慶
Name: a, dtype: object
#通過iloc和整數進行選取
In [29]: df3.iloc[2,[2,0,1]]
Out[29]:
省市 重慶
常住人口 3048
年份 2016
Name: c, dtype: object
16.DataFrame的算術運算(兩個df間計算):df1+df2
(1)兩個df進行運算時,會按行列索引進行自動對齊,行列索引重疊的部分才會進行計算,其余部分會用NaN進行填充。
(2)可以使用fill_value參數對不重疊部分進行數據填充,例如在加減法中fill_value=0,在乘除法中fill_value=1
In [2]: df1=pd.DataFrame(np.arange(12).reshape((3,4)),
...: columns=list('abcd'))
...: df2=pd.DataFrame(np.arange(20).reshape((4,5)),
...: columns=list('abcde'))
...: df1.loc[1,'b']=np.nan
In [3]: df1
Out[3]:
a b c d
0 0 1.0 2 3
1 4 NaN 6 7
2 8 9.0 10 11
In [4]: df2
Out[4]:
a b c d e
0 0 1 2 3 4
1 5 6 7 8 9
2 10 11 12 13 14
3 15 16 17 18 19
In [5]: df1+df2
Out[5]:
a b c d e
0 0.0 2.0 4.0 6.0 NaN
1 9.0 NaN 13.0 15.0 NaN
2 18.0 20.0 22.0 24.0 NaN
3 NaN NaN NaN NaN NaN
#fill_value參數填充
In [6]: df1.add(df2,fill_value=0)
Out[6]:
a b c d e
0 0.0 2.0 4.0 6.0 4.0
1 9.0 6.0 13.0 15.0 9.0
2 18.0 20.0 22.0 24.0 14.0
3 15.0 16.0 17.0 18.0 19.0
#行廣播
In [9]: s=df2.loc[1]
In [10]: s
Out[10]:
a 5
b 6
c 7
d 8
e 9
Name: 1, dtype: int32
In [11]: df2
Out[11]:
a b c d e
0 0 1 2 3 4
1 5 6 7 8 9
2 10 11 12 13 14
3 15 16 17 18 19
In [12]: df2-s
Out[12]:
a b c d e
0 -5 -5 -5 -5 -5
1 0 0 0 0 0
2 5 5 5 5 5
3 10 10 10 10 10
#列廣播必須使用算術運算方法
In [13]: s2=df2['a']
In [14]: s2
Out[14]:
0 0
1 5
2 10
3 15
Name: a, dtype: int32
In [15]: df2.sub(s2,axis='index')
Out[15]:
a b c d e
0 0 1 2 3 4
1 0 1 2 3 4
2 0 1 2 3 4
3 0 1 2 3 4
16.DataFrame的函數應用和映射:np.f(df)
(1)NumPy的ufuncs(元素級數組方法)也可用于操作pandas對象
#NumPy的ufuncs(元素級數組方法)也可用于操作pandas對象
In [17]: df3=pd.DataFrame(np.random.randn(4,3),columns=list('abc'),
...: index=list('defg'))
In [18]: df3
Out[18]:
a b c
d -1.480045 -0.533040 -1.805579
e 0.570024 0.473758 0.522302
f -1.019122 2.273182 -0.013623
g 0.025102 -0.176810 0.484197
In [19]: np.abs(df3)
Out[19]:
a b c
d 1.480045 0.533040 1.805579
e 0.570024 0.473758 0.522302
f 1.019122 2.273182 0.013623
g 0.025102 0.176810 0.484197
17.DataFrame的函數應用和映射:df.apply(f)
In [8]: df=pd.DataFrame(np.random.randn(5,6),columns=list('abcdef'))
In [9]: def f(x):
...: return pd.Series([x.min(),x.max()],index=['min','max'])
In [10]: df.apply(f)
Out[10]:
a b c d e f
min -1.437988 -2.143342 -2.393996 -1.274434 -0.668326 -1.998081
max 0.605102 1.530396 1.128361 1.097948 2.435992 0.804016
#格式化數據,數據保留2位小數
In [11]: fmt=lambda x: '%.2f' % x
...: df.applymap(fmt)
Out[11]:
a b c d e f
0 -0.56 1.53 -1.18 -1.27 2.44 -0.98
1 -1.44 1.09 -0.09 1.10 0.64 -0.08
2 -1.05 -2.14 0.06 -0.31 0.82 -2.00
3 0.61 -1.08 1.13 -0.07 -0.54 -0.80
4 0.06 0.19 -2.39 -0.29 -0.67 0.80
18.DataFrame的索引排序:df.sort_index()
默認對行進行排序,可以傳入axis改變排序軸,傳入ascending確定排序方式為降序還是升序
In [12]: df
Out[12]:
a b c d e f
0 -0.558851 1.530396 -1.182550 -1.274434 2.435992 -0.976853
1 -1.437988 1.093641 -0.091220 1.097948 0.644922 -0.081432
2 -1.045230 -2.143342 0.063647 -0.311614 0.818843 -1.998081
3 0.605102 -1.078476 1.128361 -0.068826 -0.543363 -0.797792
4 0.061240 0.185573 -2.393996 -0.291933 -0.668326 0.804016
In [13]: df.sort_index(axis='columns',ascending=False)
Out[13]:
f e d c b a
0 -0.976853 2.435992 -1.274434 -1.182550 1.530396 -0.558851
1 -0.081432 0.644922 1.097948 -0.091220 1.093641 -1.437988
2 -1.998081 0.818843 -0.311614 0.063647 -2.143342 -1.045230
3 -0.797792 -0.543363 -0.068826 1.128361 -1.078476 0.605102
4 0.804016 -0.668326 -0.291933 -2.393996 0.185573 0.061240
19.DataFrame對值排序:df.sort_values()
對Series按值排序,即s.sort_values();在dataframe中按多列排序df.sort_values(by=['columns1','columns2',...])
df.sort_values(by='c')
Out[14]:
a b c d e f
4 0.061240 0.185573 -2.393996 -0.291933 -0.668326 0.804016
0 -0.558851 1.530396 -1.182550 -1.274434 2.435992 -0.976853
1 -1.437988 1.093641 -0.091220 1.097948 0.644922 -0.081432
2 -1.045230 -2.143342 0.063647 -0.311614 0.818843 -1.998081
3 0.605102 -1.078476 1.128361 -0.068826 -0.543363 -0.797792
20.DataFrame的排名:df.rank()
rank排序可以通過傳入method參數對排名方法進行限定。
method參數 | 內容 |
---|---|
average | 默認方法,在相等分組中,為各個值平均排名 |
min | 使用整個分組的最小排名(這是我們常用的排名方式,并列第一名,第三名...) |
max | 使用整個分組的最大排名 |
first | 按值在原始數據中的出現順序分配排名 |
dense | 類似min方法,但排名總是在組間增加1,而不是組中相同的元素數 |
df2=pd.DataFrame({'b': [4.3, 7, -3, 2], 'a': [0, 1, 0, 1],
'c': [-2, 5, 8, -2.5]})
df2
Out[23]:
b a c
0 4.3 0 -2.0
1 7.0 1 5.0
2 -3.0 0 8.0
3 2.0 1 -2.5
df2.rank()
Out[24]:
b a c
0 3.0 1.5 2.0
1 4.0 3.5 3.0
2 1.0 1.5 4.0
3 2.0 3.5 1.0
21.DataFrame的常用操作匯總表
函數或方法 | 用途 |
---|---|
s.values | 獲取Series或DataFrame的值(去掉索引) |
list(s) | 將Series轉換為列表 |
x in s | 判斷x是否在Series s中,返回True或False值 |
df['label']=data | 給數據添加列,注意列長度,如果是pands數據類型則會根據索引對齊 |
df.T | 行列轉置 |
del df['label'] | 刪除列,注意是對原df刪除 |
df.reindex([]) | 對索引進行排序,添加columns參數可以對列進行排序,沒有的索引會引入NaN值 |
df.rename(index={},columns={}) | 重命名行列(修改行列標題/索引),傳入字典形式的數據,如index={"oldtext":"newtext"} |
df.index=[],df.columns=[] | 按順序重命名行列(修改行列標題/索引),賦值的列表必須與index和columns的長度一致 |
df.loc[],df.iloc[] | 通用的DataFrame索引方式,df.loc[[行label],[列label]] |
df1.add/sub/div/floordiv/mul/pow(df2) | 分別用于df1和df2之間到底加、減、除、底除、乘、指數的方法 |
df.apply(f) | 對df執行函數f的運算 |
df.sort_index() | 對行按索引進行排序,可以傳入axis改變排序軸,傳入ascending確定排序方式為降序還是升序 |
df.sort_values() | 對值進行排序,對Series按值排序,即s.sort_values();在dataframe中按多列排序df.sort_values(by=['columns1','columns2',...]) |
df.rank() | 數據排名,通過method參數限定方法,method='min'是常用的排名方法 |
以上內容根據《利用Python進行數據分析·第2版》進行整理。
參考鏈接:http://www.lxweimin.com/p/161364dd0acf