目录
核心数据结构
Series是一维,DataFrame是二维,Panel是带标签的数组,是三维
Series
创建
方法1:
s=pd.Series(np.random.randn(5), index=['a','b','c','d','e']) 如果不指定索引index,系统会自动使用0,1,2,3,4...作为索引
方法2:
使用字典
d={'a':0,'b':1,'d':3}
s=pd.Series(d,index=list('abcd')) 字典没有给c赋值,c对应的值为NaN
方法3:
使用标量创建
s=pd.Series(5,index=list('abcd')) 每个值都是一样的
特性
1.是numpy中类ndarray的对象,ndarray的方法都支持
(1)可以使用s[0] s[:5] s[2:5] s[[1,3,4]] 访问
(2)np.sin(s) np.exp(s) df.values 可以使用numpy里面的这些函数
np.asarray(df)和df.values是相同的
2.类dict(字典)中的对象
(1)可以使用字典来访问 s['a'] 访问索引是a的元素 但是访问不存在的索引会报错,但是用s.get('f')访问,如果f不存在会返回None,s.get('f',0)可以添加f索引的元素为0
(2)s['b']=3 赋值
(3)s['g']=100 添加新元素
3.标签对齐操作
s1+s2 会自动标签对齐,共同的索引元素相加,不同的索引不能计算,显示NaN
DataFrame
二维数组,有行列两个索引标签
创建
df=pd.DataFrame(data,index=index,columns=columns)
可以使用如下方式创建
一维numpy数组,list,Series构成的字典
二维numpy数组
一个Series
另外的DataFrame对象
举例:
- Series构成的字典
d={'one':pd.Series([1,2,3], index=['a','b','c']), 'two':pd.Series([1,2,3,4], index=['a','b','c','d'])}
df=pd.DataFrame(d)
one | two | |
---|---|---|
a | 1.0 | 1 |
b | 2.0 | 2 |
c | 3.0 | 3 |
d | NaN | 4 |
也可以指定行索引
df=pd.DataFrame(d,index=['d','b','a']) 会按dba顺序排列行标签,c不显示
也可以指定列索引
df=pd.DataFrame(d,icolumns=['two','three'])
- list构成的字典
d={'one':[1,2,3,4],'two':[3,4,5,6]}
df=pd.DataFrame(d)
Series中如果数据个数如果不一致可以用空值代替,但是list如果数据个数不一样会报错
- 可以使用列表套元组
data=[(1,2.2,'hello'), (2,3,'world')]
df=pd.DataFrame(data, index=['one','two'], columns=list('ABC'))
A | B | C | |
---|---|---|---|
one | 1 | 2.2 | hello |
two | 2 | 3.0 | world |
- 使用列表套字典等等
特性——列的选择、增加和删除
df=pd.DataFrame(np.random.randn(6,4), columns=['one','two','three','four'])
Out[16]:
one | two | three | four | |
---|---|---|---|---|
0 | -0.092031 | 1.116136 | 0.530261 | -1.539783 |
1 | 0.945960 | -0.194456 | 0.189686 | -0.483637 |
2 | -0.895602 | 0.573627 | 1.663476 | 0.705897 |
3 | -1.115555 | -0.049269 | 0.614421 | 0.192858 |
4 | -0.177563 | 0.601958 | 0.037909 | 0.041013 |
5 | 0.453347 | -0.197402 | 1.703294 | 0.093993 |
df['one'] 选一列
df.loc[1] 选一行
df['three']=df['one']+df['two']
del df['three'] 删除
df['flag']=df['one']>0.2 添加一列布尔值
df['five']=5 添加新列等于标量5
s=df.pop('four') 删除一列
df.insert(1,'bar',df['one']+df['two']) 在索引位置为1的地方加一列'bar',值为one和two相加
Out[18]:
one | bar | two | three | four | |
---|---|---|---|---|---|
0 | -0.092031 | 1.024105 | 1.116136 | 0.530261 | -1.539783 |
1 | 0.945960 | 0.751504 | -0.194456 | 0.189686 | -0.483637 |
2 | -0.895602 | -0.321975 | 0.573627 | 1.663476 | 0.705897 |
3 | -1.115555 | -1.164824 | -0.049269 | 0.614421 | 0.192858 |
4 | -0.177563 | 0.424396 | 0.601958 | 0.037909 | 0.041013 |
5 | 0.453347 | 0.255945 | -0.197402 | 1.703294 | 0.093993 |
df.assign(Ratio=df['one']/df['two'])
assign也是添加列,但是是复制一个新的数组,inset是在原数组上操作
assign可以使用更复杂的操作,df.assign(Ratio= lambda x: x.one-x.two)
df.assign(ABRatio=df.one/df.two).assign(BarValue= lambda x: x.ABRatio*x.bar)
Out[19]:
one | bar | <
---|