python的pandas学习笔记

import pandas as pd
import numpy as np
from pandas import Series,DataFrame
obj = Series(range(5),index=['a','a','b','b','c'])
obj
a    0
a    1
b    2
b    3
c    4
dtype: int64
obj.index.is_unique   #判断索引值是否唯一
False
obj['a']              #返回多个索引值
a    0
a    1
dtype: int64

对于DataFrame也如此

df = DataFrame(np.random.randn(4,3),index=list('aabb'))
df
012
a0.5999822.4217990.081475
a0.4206162.2654081.196068
b-1.153728-0.173130-0.098733
b0.540624-0.2868140.287023
df.ix['b']
012
b-1.153728-0.173130-0.098733
b0.540624-0.2868140.287023
# #汇总和计算描述统计
df = DataFrame([[1.4,np.nan],[7.1,-4.5],[np.nan,np.nan],[0.75,-1.3]],index=list('abcd'),columns=['one','two'])
df
onetwo
a1.40NaN
b7.10-4.5
cNaNNaN
d0.75-1.3

sum()默认对列进行求和

df.sum()
one    9.25
two   -5.80
dtype: float64
df.sum(axis = 1)            #对行
a    1.40
b    2.60
c    0.00
d   -0.55
dtype: float64

NA值会自动排除,通过skipa选项可以禁止

df.mean(axis=1,skipna=False)
a      NaN
b    1.300
c      NaN
d   -0.275
dtype: float64
df.idxmax()       #返回最大值的索引值
one    b
two    d
dtype: object
df.cumsum()     #累计型
onetwo
a1.40NaN
b8.50-4.5
cNaNNaN
d9.25-5.8

汇总统计描述describe

df.describe()
onetwo
count3.0000002.000000
mean3.083333-2.900000
std3.4936852.262742
min0.750000-4.500000
25%1.075000-3.700000
50%1.400000-2.900000
75%4.250000-2.100000
max7.100000-1.300000

对于非数值型,describe会产生另外一种汇总统计

obj = Series(['a','a','b','c']*4)
obj
0     a
1     a
2     b
3     c
4     a
5     a
6     b
7     c
8     a
9     a
10    b
11    c
12    a
13    a
14    b
15    c
dtype: object
obj.describe()
count     16
unique     3
top        a
freq       8
dtype: object
  • 相关系数与协方差 唯一值、值计数以及成员资格

obj = Series(['c','a','d','a','a','b','b','c','c'])
uniques = obj.unique()
uniques
array([‘c’, ‘a’, ‘d’, ‘b’], dtype=object) 返回的唯一值是未排序的,如果需要则可以再次进行排序(unique.sort())
obj.value_counts()
c 3 a 3 b 2 d 1 dtype: int64 Series值频统计是按降序排列。value_counts还是一个顶级的pandas方法,可以用于任何数组和序列
pd.value_counts(obj.values,sort=False)
a 3 c 3 b 2 d 1 dtype: int64 isin,它用于判断矢量化的成员资格,可用于选取Series中或DataFrame列中数据的子集
mask = obj.isin(['b','c'])
mask
0 True 1 False 2 False 3 False 4 False 5 True 6 True 7 True 8 True dtype: bool
obj[mask]
0 c 5 b 6 b 7 c 8 c dtype: object
data = DataFrame({
        'Qu1':[1,3,4,3,4],
        'Qu2':[2,3,1,2,3],
        'Qu3':[1,5,2,4,4]
    })
data
Qu1Qu2Qu3
0121
1335
2412
3324
4434
#统计DataFrame的每一列中元素1,2,3,4,5出现的频率,缺失值用0填
result = data.apply(pd.value_counts).fillna(0)
result
Qu1Qu2Qu3
11.01.01.0
20.02.01.0
32.02.00.0
42.00.02.0
50.00.01.0
# #处理缺失数据
string_data = Series(['aardvark','artichoke',np.nan,'avocado'])
string_data
0 aardvark 1 artichoke 2 NaN 3 avocado dtype: object
string_data.isnull()
0 False 1 False 2 True 3 False dtype: bool python内置的None值也会被当做NA处理
string_data[0] = None
string_data
0 None 1 artichoke 2 NaN 3 avocado dtype: object
string_data.isnull()
0 True 1 False 2 True 3 False dtype: bool Na处理方法 dropna 根据各标签的值中是否存在缺失数据对轴标签进行过滤,可通过阈值调节对缺失值的容忍度 fillna 用指定值或插值方法(如ffill或bfill)填充缺失数据 isnull 返回一个含有布尔值的对象,这些布尔值表示哪些是缺失 notnull isnull的否定式 # #滤除缺失值
from numpy import nan as NA
data = Series([1,NA,3.5,NA,7])
data.dropna()
0 1.0 2 3.5 4 7.0 dtype: float64
#也可以通过布尔值索引达到目的
data[data.notnull()]
0 1.0 2 3.5 4 7.0 dtype: float64
#dropna默认丢弃任何含有缺失值的行
data = DataFrame([[1,6.5,3],[1,NA,NA],[NA,NA,NA],[NA,6.5,3]])
cleaned = data.dropna()
cleaned
012
01.06.53.0
#传入how = 'all'将只丢弃全为NA的哪些行
data.dropna(how = 'all')
012
01.06.53.0
11.0NaNNaN
3NaN6.53.0
data[4] = NA
data
0124
01.06.53.0NaN
11.0NaNNaNNaN
2NaNNaNNaNNaN
3NaN6.53.0NaN
#要用这种方法丢弃列,只需传入axis=1即可
data.dropna(axis=1,how='all')
012
01.06.53.0
11.0NaNNaN
2NaNNaNNaN
3NaN6.53.0
df = DataFrame(np.random.randn(7,3));df
012
0-1.051300-0.526329-0.204891
1-0.977547-1.7060290.946824
20.540648-1.228170-1.180031
3-0.320932-0.6673050.239980
4-0.303641-1.0969180.355744
5-0.4241761.880769-0.013825
60.6437250.301759-1.520921
df.ix[:4,1] = NA;df
012
0-1.051300NaN-0.204891
1-0.977547NaN0.946824
20.540648NaN-1.180031
3-0.320932NaN0.239980
4-0.303641NaN0.355744
5-0.4241761.880769-0.013825
60.6437250.301759-1.520921
df.ix[:2,2] = NA;df
012
0-1.051300NaNNaN
1-0.977547NaNNaN
20.540648NaNNaN
3-0.320932NaN0.239980
4-0.303641NaN0.355744
5-0.4241761.880769-0.013825
60.6437250.301759-1.520921
df
012
0-1.051300NaNNaN
1-0.977547NaNNaN
20.540648NaNNaN
3-0.320932NaN0.239980
4-0.303641NaN0.355744
5-0.4241761.880769-0.013825
60.6437250.301759-1.520921
df.dropna(thresh=2)
012
3-0.320932NaN0.239980
4-0.303641NaN0.355744
5-0.4241761.880769-0.013825
60.6437250.301759-1.520921
help(df.dropna)
Help on method dropna in module pandas.core.frame: dropna(self, axis=0, how=’any’, thresh=None, subset=None, inplace=False) method of pandas.core.frame.DataFrame instance Return object with labels on given axis omitted where alternately any or all of the data are missing Parameters ———- axis : {0 or ‘index’, 1 or ‘columns’}, or tuple/list thereof Pass tuple or list to drop on multiple axes how : {‘any’, ‘all’} * any : if any NA values are present, drop that label * all : if all values are NA, drop that label thresh : int, default None int value : require that many non-NA values subset : array-like Labels along other axis to consider, e.g. if you are dropping rows these would be a list of columns to include inplace : boolean, default False If True, do operation inplace and return None. Returns ——- dropped : DataFrame
df.fillna(0)
012
0-1.0513000.0000000.000000
1-0.9775470.0000000.000000
20.5406480.0000000.000000
3-0.3209320.0000000.239980
4-0.3036410.0000000.355744
5-0.4241761.880769-0.013825
60.6437250.301759-1.520921
#若通过一个字典调用fillna,就可以实现对不同的列填充不同的值
df.fillna({1:0.5,3:-1})
012
0-1.0513000.500000NaN
1-0.9775470.500000NaN
20.5406480.500000NaN
3-0.3209320.5000000.239980
4-0.3036410.5000000.355744
5-0.4241761.880769-0.013825
60.6437250.301759-1.520921

fillna默认会返回新对象,但也可以对现有对象进行就地修改

_ = df.fillna(0,inplace=True)
df
012
0-1.0513000.0000000.000000
1-0.9775470.0000000.000000
20.5406480.0000000.000000
3-0.3209320.0000000.239980
4-0.3036410.0000000.355744
5-0.4241761.880769-0.013825
60.6437250.301759-1.520921

对reindex有效的哪些插值方法也可以用于fillna

df = DataFrame(np.random.randn(6,3))
df
012
00.9368740.226055-0.008118
1-1.8856680.947839-0.344767
2-1.620408-0.8957141.133733
31.4424550.9597080.107022
4-1.4558460.5724861.087657
51.189054-1.623793-0.334216
df.ix[2:,1] = NA; df.ix[4:,2] = NA
df
012
00.9368740.226055-0.008118
1-1.8856680.947839-0.344767
2-1.620408NaN1.133733
31.442455NaN0.107022
4-1.455846NaNNaN
51.189054NaNNaN
# ffill :将有效的观察传播到下一个有效的观察
df.fillna(method='ffill')
012
00.9368740.226055-0.008118
1-1.8856680.947839-0.344767
2-1.6204080.9478391.133733
31.4424550.9478390.107022
4-1.4558460.9478390.107022
51.1890540.9478390.107022
help(df.fillna)
Help on method fillna in module pandas.core.frame: fillna(self, value=None, method=None, axis=None, inplace=False, limit=None, downcast=None, **kwargs) method of pandas.core.frame.DataFrame instance Fill NA/NaN values using the specified method Parameters ———- value : scalar, dict, Series, or DataFrame Value to use to fill holes (e.g. 0), alternately a dict/Series/DataFrame of values specifying which value to use for each index (for a Series) or column (for a DataFrame). (values not in the dict/Series/DataFrame will not be filled). This value cannot be a list. method : {‘backfill’, ‘bfill’, ‘pad’, ‘ffill’, None}, default None Method to use for filling holes in reindexed Series pad / ffill: propagate last valid observation forward to next valid backfill / bfill: use NEXT valid observation to fill gap axis : {0, 1, ‘index’, ‘columns’} inplace : boolean, default False If True, fill in place. Note: this will modify any other views on this object, (e.g. a no-copy slice for a column in a DataFrame). limit : int, default None If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is the maximum number of entries along the entire axis where NaNs will be filled. downcast : dict, default is None a dict of item->dtype of what to downcast if possible, or the string ‘infer’ which will try to downcast to an appropriate equal type (e.g. float64 to int64 if possible) See Also ——– reindex, asfreq Returns ——- filled : DataFrame
df.fillna(method='ffill',limit=2)
012
00.9368740.226055-0.008118
1-1.8856680.947839-0.344767
2-1.6204080.9478391.133733
31.4424550.9478390.107022
4-1.455846NaN0.107022
51.189054NaN0.107022
data = Series([1,NA,3.5,NA,7])
#使用平均值填充
data.fillna(data.mean())
0    1.000000
1    3.833333
2    3.500000
3    3.833333
4    7.000000
dtype: float64
  • 层次化索引
data = Series(np.random.randn(10),
              index=[['a','a','a','b','b','b','c','c','d','d'],[1,2,3,1,2,3,1,2,2,3]])
data
a  1   -0.520847
   2    0.858349
   3   -1.048257
b  1    0.281738
   2    0.757592
   3    0.032117
c  1    0.526343
   2   -2.281655
d  2   -0.017352
   3    0.047178
dtype: float64
data.index
MultiIndex(levels=[[u’a’, u’b’, u’c’, u’d’], [1, 2, 3]], labels=[[0, 0, 0, 1, 1, 1, 2, 2, 3, 3], [0, 1, 2, 0, 1, 2, 0, 1, 1, 2]])
#对一个层次索引
data['b']
1    0.281738
2    0.757592
3    0.032117
dtype: float64
data['b':'c']
b  1    0.281738
   2    0.757592
   3    0.032117
c  1    0.526343
   2   -2.281655
dtype: float64
data.ix[['b','d']]
b  1    0.281738
   2    0.757592
   3    0.032117
d  2   -0.017352
   3    0.047178
dtype: float64
data[:,2]
a    0.858349
b    0.757592
c   -2.281655
d   -0.017352
dtype: float64
data
a  1   -0.520847
   2    0.858349
   3   -1.048257
b  1    0.281738
   2    0.757592
   3    0.032117
c  1    0.526343
   2   -2.281655
d  2   -0.017352
   3    0.047178
dtype: float64

层次化索引在数据重塑和基于分组的操作中扮演着重要的角色。可以使用unstack方法被重新安排到一个DataFrame中

data.unstack()
123
a-0.5208470.858349-1.048257
b0.2817380.7575920.032117
c0.526343-2.281655NaN
dNaN-0.0173520.047178
#unstack的逆运算是stack
data.unstack().stack()
a  1   -0.520847
   2    0.858349
   3   -1.048257
b  1    0.281738
   2    0.757592
   3    0.032117
c  1    0.526343
   2   -2.281655
d  2   -0.017352
   3    0.047178
dtype: float64
frame = DataFrame(np.arange(12).reshape(4,3),index=[['a','a','b','b'],[1,2,1,2]],
                  columns=[['Ohio','Ohio','Colorado'],['Green','Red','Green']])
frame
OhioColorado
GreenRedGreen
a1012
2345
b1678
291011
frame.index.names = ['key1','key2']
frame.columns.names = ['state','color']
frame
stateOhioColorado
colorGreenRedGreen
key1key2
a1012
2345
b1678
291011
frame['Ohio']
colorGreenRed
key1key2
a101
234
b167
2910

swaplevel接受两个级别编号或名称并返回一个互换了级别的新对象(但数据不会发生变化)

frame.swaplevel('key1','key2')
stateOhioColorado
colorGreenRedGreen
key2key1
1a012
2a345
1b678
2b91011
frame
stateOhioColorado
colorGreenRedGreen
key1key2
a1012
2345
b1678
291011
stortlevel则根据单个级别中的值对数据进行排序(稳定的)
#两级分层,取0,1,分别表示第一层,第二层
frame.sortlevel(1)
stateOhioColorado
colorGreenRedGreen
key1key2
a1012
b1678
a2345
b291011
frame
stateOhioColorado
colorGreenRedGreen
key1key2
a1012
2345
b1678
291011
frame.swaplevel(0,1)
stateOhioColorado
colorGreenRedGreen
key2key1
1a012
2a345
1b678
2b91011
frame.swaplevel(0,1).sortlevel(0)
stateOhioColorado
colorGreenRedGreen
key2key1
1a012
b678
2a345
b91011
# #根据级别汇总统计
frame
stateOhioColorado
colorGreenRedGreen
key1key2
a1012
2345
b1678
291011
frame.sum(level='key2')
stateOhioColorado
colorGreenRedGreen
key2
16810
2121416
frame.sum(level='color',axis=1)
colorGreenRed
key1key2
a121
284
b1147
22010
# #使用DataFrame的列
frame = DataFrame({
        'a':range(7),
        'b':range(7,0,-1),
        'c':['one','one','one','two','two','two','two'],
        'd':[0,1,2,0,1,2,3]
        })
frame
abcd
007one0
116one1
225one2
334two0
443two1
552two2
661two3

DataFrame的set_index函数会将其中一个或多个列转换为行索引,并创建一个新的DataFrame

frame2 = frame.set_index(['c','d'])
frame2
ab
cd
one007
116
225
two034
143
252
361

默认情况下,哪些列会从DataFrame中移除,但也可以将其保留下来

frame.set_index(['c','d'],drop=False)
abcd
cd
one007one0
116one1
225one2
two034two0
143two1
252two2
361two3

reset_index的功能跟set_index刚好相反,层次化索引的级别会被转移到列里

frame2.reset_index()
cdab
0one007
1one116
2one225
3two034
4two143
5two252
6two361

整数索引

ser = Series(np.arange(3.))
#会以为是倒数第一的索引,其实报错,整数的索引值为0,1,2
ser[-1]
————————————————————————— KeyError Traceback (most recent call last) in () 1 #会以为是倒数第一的索引,其实报错,整数的索引值为0,1,2 —-> 2 ser[-1] C:\Anaconda\Anaconda2\lib\site-packages\pandas\core\series.pyc in __getitem__(self, key) 558 def __getitem__(self, key): 559 try: –> 560 result = self.index.get_value(self, key) 561 562 if not lib.isscalar(result): C:\Anaconda\Anaconda2\lib\site-packages\pandas\indexes\base.pyc in get_value(self, series, key) 1909 try: 1910 return self._engine.get_value(s, k, -> 1911 tz=getattr(series.dtype, ‘tz’, None)) 1912 except KeyError as e1: 1913 if len(self) > 0 and self.inferred_type in [‘integer’, ‘boolean’]: pandas\index.pyx in pandas.index.IndexEngine.get_value (pandas\index.c:3234)() pandas\index.pyx in pandas.index.IndexEngine.get_value (pandas\index.c:2931)() pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:3891)() pandas\hashtable.pyx in pandas.hashtable.Int64HashTable.get_item (pandas\hashtable.c:6527)() pandas\hashtable.pyx in pandas.hashtable.Int64HashTable.get_item (pandas\hashtable.c:6465)() KeyError: -1L 相反,对于一个非整数索引,就没有这样的歧义
ser2 = Series(np.arange(3.),index=['a','b','c'])
ser2[-1]
2.0
ser.ix[:1]
0 0.0 1 1.0 dtype: float64 如果需要可靠的,不考虑索引类型的,基于位置的索引,可以使用Series的iget_value方法和Dataframe的irow和icol方法
ser3 = Series(range(3),index=[-5,1,3])
ser3
-5 0 1 1 3 2 dtype: int64
ser3.iget_value(2)
C:\Anaconda\Anaconda2\lib\site-packages\ipykernel\__main__.py:1: FutureWarning: iget_value(i) is deprecated. Please use .iloc[i] or .iat[i] if __name__ == ‘__main__’: 2
frame = DataFrame(np.arange(6).reshape(3,2),index=[2,0,1])
frame
01
201
023
145
frame.irow(1)
C:\Anaconda\Anaconda2\lib\site-packages\ipykernel\__main__.py:1: FutureWarning: irow(i) is deprecated. Please use .iloc[i]
  if __name__ == '__main__':





0    2
1    3
Name: 0, dtype: int32
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值