DateFrame对象:新建一个的常用方法是传递一个dict对象给DateFrame()构造函数,dict对象以每一列的名称作为键,每个键都有一个数值作为值(字典的键是DateFrame的列名,值构成一列)
**1.**frame=pd.DateFrame(dict{})或者是, frame=pd.DateFrame([ ],colums=,index=)
data = {'color':['blue','green','yellow','red','white'],
'object':['ball','pen','pencil','paper','mug'],
'price':[1.2,1.0,0.6,0.9,1.7]}
frame = pd.DataFrame(data)
输出
color object price
0 blue ball 1.2
1 green pen 1.0
2 yellow pencil 0.6
3 red paper 0.9
4 white mug 1.7
嵌套生成dataframe对象
nestdict = {'red':{2012:22, 2013:33},
'white':{2011:13, 2012:22, 2013:16},
'blue':{2011:17, 2012:27, 2013:18}}
frame2 = pd.DataFrame(nestdict)
frame2
Out[14]:
red white blue
2011 NaN 13 17
2012 22.0 22 27
2013 33.0 16 18
pandas会将外部的键解释成列名称,内部的键解释为用作索引的标签
还可以用columns指定需要的列 :frame = pd.DataFrame(data,columns=[‘object’, ‘price’])
还可以用index指定需要的标签:frame = pd.DataFrame(data,index=[‘one’, ‘two’, 等])
frame.index/columns/values可以知道各个属性,也可以用列名来索引列
赋值:
可以用name属性为index和colums这两个二级结构指定标签,例如frame.index.name=‘id’
frame.columns.name=‘item’
①:frame['new'] = 12
输出:
color object price new
0 blue ball 1.2 12
1 green pen 1.0 12
2 yellow pencil 0.6 12
3 red paper 0.9 12
4 white mug 1.7 12
也可以用ser = pd.Series( np.range(5) ) frame [‘new’] = ser对DateFrame对象进行赋值操作
②
单个元素赋值 frame[‘price’][2] = xxx
元素所属关系
- isin()对dataframe对象也适用
frame.isin([1.0,'pen']) #只得到了包含布尔值的dataframe对象,满足
Out[7]: #从属关系的为True,如果将其返回将得到一个新的dataframe对象
color object price new
0 False False False False
1 False True True False
2 False False False False
3 False False False False
4 False False False False
把上述返回结果作为条件,将得到一个新对象其中包含满足条件的元素:
frame[frame.isin([1.0,'pen'])]
输出:
color object price new
0 NaN NaN NaN NaN
1 NaN pen 1.0 NaN
2 NaN NaN NaN NaN
3 NaN NaN NaN NaN
4 NaN NaN NaN NaN
删除
del命令,删除数据整列
drop():删除index对象,
注意:在dataframe中使用的时候,如果删除列,则需要加指定列的索引,按照列的方向删除,axis=1
数据集合
1.groupby():如果想使用color列的组标签。计算price列的均值,就可以用此函数
frame = pd.DataFrame({'color':['white','red','green','red','green'],
'object':['pen','pencil','pencil','ashtray','pen'],
'price':[5.56,4.20,1.30,0.56,2.75],
'price2':[4.75,4.12,1.60,0.75,3.15]})
输出:
color object price price2
0 white pen 5.56 4.75
1 red pencil 4.20 4.12
2 green pencil 1.30 1.60
3 red ashtray 0.56 0.75
4 green pen 2.75 3.15
group = frame['price'].groupby(frame['color']) 或者是frame.groupby(['color'])['price']
#相当于是将color列打包成一组,然后对每一个price进行索引
group.groups #查看分组情况
>>>{'green': Int64Index([2, 4], dtype='int64'),
'red': Int64Index([1, 3], dtype='int64'),
'white': Int64Index([0], dtype='int64')}
接下来就可以运用其他函数来计算各种值,例如group.mean(),group.sum()
也可以用多列,按照等级关系分组
ggroup = frame['price'].groupby([frame['color'],frame['object']])
ggroup.groups #查看分组
输出:
{('green', 'pen'): Int64Index([4], dtype='int64'),
('green', 'pencil'): Int64Index([2], dtype='int64'),
('red', 'ashtray'): Int64Index([3], dtype='int64'),
('red', 'pencil'): Int64Index([1], dtype='int64'),
('white', 'pen'): Int64Index([0], dtype='int64')}
等一系列操作
最方便的就是一次把所有的分组依据和计算方法都指定好,而无需定义任何中间变量
frame[['price','price2']].groupby(frame['color']).mean() 或者是
frame.groupby(frame['color']).mean()
groupby还支持组迭代:
for name,group in frame.groupby('color'):
print (name)
print (group)
out:
green
color object price price2
2 green pencil 1.30 1.60
4 green pen 2.75 3.15
red
color object price price2
1 red pencil 4.20 4.12
3 red ashtray 0.56 0.75
white
color object price price2
0 white pen 5.56 4.75
额外记忆
Pandas(可用level来指定获取哪个层级的描述性和概括统计量)
Series、DataFrame都可以使用的函数:
相关性:corr() 协方差:cov()
corrwith():可以计算dataframe对象的行或列与series对象或其他dataframe对象元素两两之间的相关性
1.pandas的index对象有is_unique属性,可以判断数据结构(series和dataframe)中是否存在重复的索引项
4.isnull() notnull()函数用来识别没有对应元素的索引
1. dropna(): 删除数据中的所有NaN,或者是使用ser[ser.notnull( )]实现直接过滤。 #注意,dataframe使用此方法会删除含有NaN的所有行或者列,需使用how=‘all’,删除元素均为NaN的行或列
2.fillna( ):用其他值取代替nan,若要将不同列的nan替换为不同的元素,指定出列名称及要替换的元素即可
3.unstack(): 把使用的等级索引Series对象转换为一个简单的dataframe对象,把第二列索引转换为响应的列,stack()与之相反
Series存储一维数据
1.a = pd.Series([ ], index=[字符串类型])
2.reindex()可以更换series对象的索引,根据新标签序列,重新调整原series元素,生成一个新的series对象
2.series.unique():series中的元素去重 、value_counts( ):不仅去重,还返回各个元素出现的次数
3.isin( ): 判断函数所属关系
排序:5. ser.sort_index(ascending):返回一个新对象,默认是True按照A-Z排序,
6.ser.sort_values()对Series对象排序
7.ser.rank(method,ascending):排位次,输出的值是排序后的位次值
DateFrame对象:
3.frame.apply(func,axis=): 可以在dataframe上调用刚定义的函数,默认处理列,令其等于1,则处理行
4. frame.sum()/mean()/describe():计算多个统计量,可以用level指出求哪一行的统计量
排序:5. frame.sort_index(axis)[sort_values(bu=)]:指定列或行,默认列,by指定对哪一列进行排序,可以是多个
6.frame.swaplevel( ):以要互换位置的两个层级的名称为参数,返回交换位置的一个新对象,各元素顺序保持不变
读取数据:
1. pd.read_csv/excel, hdf, sql, json, html, stata, clipboard, pickle, msgpack, gbq/(header,names,skiprows):数据无表头时header=None,会自动添加表头,可以用names指定表头, skiprows排除多余行,前五行 s…=5,第五行 s…=[5]
2.pd.to_csv/excel, hdf, sql, json, html, stata, clipboard, pickle, msgpack, gbq/(header,index,na_rep)header和index的值设为False可以避免索引和列的写入
注意:NaN写入后显示为空字段,na_rep可以将空字段替换为想要得到值,常用有NULL、0和NaN
3.read_table(’ ', seq=):读取文本文件,需要指定分隔符,分隔符可以匹配正则表达式使用
4.read_csv(等文件)指定起始行skiprows=xxx,往后读多少行nrows=x