1. Numpy和Pandas的不同:
Numpy是列表形式,没有数值标签;Pandas是字典形式
2. Pandas的两个主要的数据结构Series和DateFrame
1. Series索引在左边,值在右边。若未指定索引,自动创建0到N-1(N为长度)的整数型索引
import pandas as pd
import numpy as np
s=pd.Series([1,3,6,np.nan,44,1])
print(s)
输出:
0 1.0 1 3.0 2 6.0 3 NaN 4 44.0 5 1.0 dtype: float64
2. numpy.random.randn(6,4) 返回6行4列,0~1的随机值
3. DataFrame:表格型数据结构,包含一组有序的数列,每列都是不同的值类型(数值,字符串,布尔值)。DataFrame既有行索引,也有列索引。可以被看做由Series组成的大字典。
import pandas as pd
import numpy as np
dates=pd.date_range('20160101',periods=6)
df=pd.DataFrame(np.random.randn(6,4),index=dates,columns=['a','b','c','d']) #指定index为dates
print(df)
a b c d 2016-01-01 -0.680950 -0.790554 -0.813075 -0.544137 2016-01-02 -2.011874 1.961104 0.199840 -0.892645 2016-01-03 -0.158728 0.374837 -0.805338 -1.004351 2016-01-04 -1.105633 1.287782 1.228255 1.046915 2016-01-05 -0.158540 -0.485821 0.810580 -1.085436 2016-01-06 0.381288 -2.490325 -0.908194 1.044473
4. DataFrame的一些简单应用
1. 输出DataFrame的第b列数据
print(df['b'])
输出:
2016-01-01 -1.047603 2016-01-02 -0.838383 2016-01-03 -0.222159 2016-01-04 -0.743130 2016-01-05 -0.189042 2016-01-06 -0.794491 Freq: D, Name: b, dtype: float64
2.创建一组没有给定行标签和列标签的数据
df1=pd.DataFrame(np.arange(12).reshape((3,4)))
输出: 0 1 2 3
0 0 1 2 3 1 4 5 6 7 2 8 9 10 11
3. 创建对每一列数据特殊对待的对象
df2 = pd.DataFrame({'A' : 1.,
'B' : pd.Timestamp('20130102'),
'C' : pd.Series(1,index=list(range(4)),dtype='float32'),
'D' : np.array([3] * 4,dtype='int32'),
'E' : pd.Categorical(["test","train","test","train"]),
'F' : 'foo'})
print(df2)
输出: A B C D E F
0 1.0 2013-01-02 1.0 3 test foo
1 1.0 2013-01-02 1.0 3 train foo
2 1.0 2013-01-02 1.0 3 test foo
3 1.0 2013-01-02 1.0 3 train foo
4. dtype查看数据的类型
print(df2.dtypes)
输出: A float64 B datetime64[ns] C float32 D int32 E category F object dtype: object
5.转置
print(df2.T)
6. 选择数据
1.数据源
import pandas as pd
dates=pd.date_range('20130101',periods=6)
df=pd.DataFrame(np.arange(24).reshape((6,4)),index=dates,columns=['A','B','C','D'])
df