pandas是基于numpy数组结构的,但二者最大的不同是pandas是专门为处理表格和混杂数据设计的,比较契统计分析中的表结构,而numpy更适合处理统一的数值数组数据。
import numpy as np
import pandas as pd
chengji=[['', '期末', '期末'], ['张三', 50, 80], ['李四', 60, 90], ['王老五', 70, 89]]
chengji_array=np.array(chengji)
print(chengji,'\n')
print(chengji_array,'\n')
dic={ '期中':[50,60,70], '期末':[80,90,89] }
chengji_dataframe=pd.DataFrame(dic, index=['张三', '李四', '王老五'])
print(chengji_dataframe)
output:
[['', '期末', '期末'], ['张三', 50, 80], ['李四', 60, 90], ['王老五', 70, 89]]
[['' '期末' '期末']
['张三' '50' '80']
['李四' '60' '90']
['王老五' '70' '89']]
期中 期末
张三 50 80
李四 60 90
王老五 70 89
Process finished with exit code 0
Pandas数据结构:
1.Series(一维数据),索引+一维数组
2.DataFrame(多维数据),行列索引+多维数组
1.Series相关内容
import numpy as np
import pandas as pd
s1=pd.Series(np.arange(3),np.arange(1,4))
print(s1,'\n') #pd.Series(obj,index,dtype)
s2=pd.Series({'a':100,'b':150})
print(s2,'\n')
##############Series对象的属性##################
print('values:',s2.values)
print('index:',s2.index)
print('s2的形状:',s2.shape)
print('s2的元素数量:',s2.size)
print('s2的维度:',s2.ndim)
###############Series对象的切片操作##############
print('s2中a的值:',s2['a'])
print('s2中a,b的值:','\n',s2['a':'b']) #中间用冒号隔开!
print('s2中前两行的数据:','\n',s2[0:2])
output:
1 0
2 1
3 2
dtype: int32
a 100
b 150
dtype: int64
values: [100 150]
index: Index(['a', 'b'], dtype='object')
s2的形状: (2,)
s2的元素数量: 2
s2的维度: 1
s2中a的值: 100
s2中a,b的值:
a 100
b 150
dtype: int64
s2中前两行的数据:
a 100
b 150
dtype: int64
Process finished with exit code 0
Series的操作-类似字典
◆通过自定义索引访问
◆保留字in操作:判定给定的索引值是否在索引序列中
◆使用.get()方法:类似于字典中的get方法
import pandas as pd
b=pd.Series({'math':99,'eng':98,'chinese':97})
print(b)
print('b同学的数学成绩:',b['math'])
print('eng' in b)
print('b同学的语文成绩:',b.get('chinese'))
print('b同学的体育成绩:',b.get('PE',100))
output:
math 99
eng 98
chinese 97
dtype: int64
b同学的数学成绩: 99
True
b同学的语文成绩: 97
b同学的体育成绩: 100
Process finished with exit code 0
Series常用函数
