Pandas数据处理(一)
import pandas as pd
import numpy as np
#利用numpy生成一组DataFrome数据
df=pd.DataFrame(np.arange(16).reshape(4,4))
print(df)
–out
0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
3 12 13 14 15
#我们看到有一行,竖我们没有指定没结果却出现了,
#那因为DataFrome是我们的二维数列,产生了行索引和竖索引
#当然我们也可以指定索引数值
df=pd.DataFrame(np.arange(16,32).reshape(4,4),index=[‘a’,‘b’,‘c’,‘d’],columns=[‘w’,‘x’,‘y’,‘z’])
print(df)
–out
w x y z
a 16 17 18 19
b 20 21 22 23
c 24 25 26 27
d 28 29 30 31
#DataFrome 导入字典
a={‘Id’:[‘001’,‘002’,‘003’],‘name’:[‘小猫’,‘小狗’,‘小狼’],‘sex’:[‘女’,‘男’,‘男’]}
df=pd.DataFrame(a)
print(df)
–out
Id name sex
0 001 小猫 女
1 002 小狗 男
2 003 小狼 男
#pandas果然功能强大,这也是我非常喜欢的一个地方
#查看行索引
print(df.index)
–out
RangeIndex(start=0, stop=3, step=1)
#查看列索引
print(df.columns)
–out
Index([‘Id’, ‘name’, ‘sex’], dtype=‘object’)
#查看数据
print(df.values)
–out
[[‘001’ ‘小猫’ ‘女’]
[‘002’ ‘小狗’ ‘男’]
[‘003’ ‘小狼’ ‘男’]]
#查看类型
print(type(df))
–out
<class ‘pandas.core.frame.DataFrame’>
#查看列表中数据类型
print(type(df))
–out
Id object
name object
sex object
dtype: object
#查看数据维度
print(df.shape)
–out
(3, 3)
#按要求显示数据
print(df.head(1))
–out
Id name sex
0 001 小猫 女
#显示倒数第一行
print(df.tail(1))
–out
Id name sex
2 003 小狼 男
#显示列表信息
print(df.info())
–out
<class ‘pandas.core.frame.DataFrame’>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
Column Non-Null Count Dtype
0 Id 3 non-null object
1 name 3 non-null object
2 sex 3 non-null object
dtypes: object(3)
memory usage: 200.0+ bytes
None