本文主要介绍pandas中的两种数据结构:series,dataframe。
import numpy as np
import pandas as pd
"""Series的构建"""
"""通过list构建"""
ser_obj = pd.Series(range(10, 20))
print(ser_obj)
"""通过dict构建"""
year_data={2001:17.8,2002:18.4,2003:20.1}
ser_obj2=pd.Series(year_data)
print(ser_obj2)
"""获取数据和索引"""
print(ser_obj.values)
print(ser_obj.index)
"""预览数据"""
"获取前n行,默认是前五行"
print(ser_obj.head(3))
"获取后n行,默认是后五行"
print(ser_obj.tail(2))
"""通过索引获取数据"""
print(ser_obj[0])
print(ser_obj[8])
"""构建DataFrame"""
"通过数组构建"
array=np.random.randn(5,4)
print(array)
df_obj=pd.DataFrame(array)
print(df_obj.head())
"通过dict构建DataFrame"
dict_data = {'A': 1.,
'B': pd.Timestamp('20161223'),
'C': pd.Series(1, index=list(range(4)),dtype='float32'),
'D': np.array([3] * 4,dtype='int32'),
'E': pd.Categorical(["Python","Java","C++","C#"]),
'F': 'wangxiaocao' }
#print dict_data
df_obj2 = pd.DataFrame(dict_data)
print(df_obj2.head())
"通过索引获取数据"
print(df_obj2['F'])
"增加与删除列"
df_obj2['G']=df_obj2['D']+54
print(df_obj2.head())
del df_obj2['G']
print(df_obj2.head())
结果:
E:\pythonspace\shujufenxi\venv\Scripts\python.exe E:/pythonspace/shujufenxi/pandas_数据结构.py
0 10
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
dtype: int64
2001 17.8
2002 18.4
2003 20.1
dtype: float64
[10 11 12 13 14 15 16 17 18 19]
RangeIndex(start=0, stop=10, step=1)
0 10
1 11
2 12
dtype: int64
8 18
9 19
dtype: int64
10
18
[[-0.28795039 -1.19827525 -0.03696809 -0.04624722]
[-1.00289717 -0.322037 0.37673109 -2.48401446]
[-0.43770168 0.42447045 0.40908983 -1.1165361 ]
[ 0.18840976 -1.75259833 1.75949495 -0.77452575]
[-1.10276159 -1.54548383 -0.27926888 -0.07990538]]
0 1 2 3
0 -0.287950 -1.198275 -0.036968 -0.046247
1 -1.002897 -0.322037 0.376731 -2.484014
2 -0.437702 0.424470 0.409090 -1.116536
3 0.188410 -1.752598 1.759495 -0.774526
4 -1.102762 -1.545484 -0.279269 -0.079905
A B C D E F
0 1.0 2016-12-23 1.0 3 Python wangxiaocao
1 1.0 2016-12-23 1.0 3 Java wangxiaocao
2 1.0 2016-12-23 1.0 3 C++ wangxiaocao
3 1.0 2016-12-23 1.0 3 C# wangxiaocao
0 wangxiaocao
1 wangxiaocao
2 wangxiaocao
3 wangxiaocao
Name: F, dtype: object
A B C D E F G
0 1.0 2016-12-23 1.0 3 Python wangxiaocao 57
1 1.0 2016-12-23 1.0 3 Java wangxiaocao 57
2 1.0 2016-12-23 1.0 3 C++ wangxiaocao 57
3 1.0 2016-12-23 1.0 3 C# wangxiaocao 57
A B C D E F
0 1.0 2016-12-23 1.0 3 Python wangxiaocao
1 1.0 2016-12-23 1.0 3 Java wangxiaocao
2 1.0 2016-12-23 1.0 3 C++ wangxiaocao
3 1.0 2016-12-23 1.0 3 C# wangxiaocao
Process finished with exit code 0