#每天一点点#
python pandas 基本介绍
1:Series可以保存不同的数据类型
Series是Pandas中的一维数据结构,类似于Python中的列表和Numpy中的Ndarray,
不同之处在于:Series是一维的,能存储不同类型的数据,有一组索引与元素对应。
#Series 简单示例
import numpy as np
import pandas as pd
s = pd.Series([1,3,6,np.nan,44,1])
输出结果 ??????
输出结果 ??????
2:DataFrame
dates = pd.date_range('20160101',periods=6)
输出结果 ??????
输出结果 ??????
定义一个6行4列随机数据,以dates日期为行索引,以abcd为列索引
df = pd.DataFrame(np.random.randn(6,4),index=dates,columns=['a','b','c','d'])
输出结果 ??????
输出结果 ??????
#默认行,列索引
df1 = pd.DataFrame(np.arange(12).reshape((3,4)))
输出结果 ??????!
输出结果 ??????
用字典的方式
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':'foot' })
输出结果 ??????
输出结果 ??????
dataframe的属性形式
df2.dtypes
输出结果 ??????
A float64
B datetime64[ns]
C float32
D int32
E category
F object
dtype: object
输出结果 ??????
输出所有列的标序
df2.index
输出结果 ??????
Int64Index([0, 1, 2, 3], dtype=‘int64’)
输出结果 ??????
输出所有行的标序
df2.columns
输出结果 ??????
Index([‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’], dtype=‘object’)
输出结果 ??????
输出所有values
df2.values
输出结果 ??????
array([[1.0, Timestamp(‘2013-01-02 00:00:00’), 1.0, 3, ‘test’, ‘foot’],
[1.0, Timestamp(‘2013-01-02 00:00:00’), 1.0, 3, ‘train’, ‘foot’],
[1.0, Timestamp(‘2013-01-02 00:00:00’), 1.0, 3, ‘test’, ‘foot’],
[1.0, Timestamp(‘2013-01-02 00:00:00’), 1.0, 3, ‘train’, ‘foot’]], dtype=object)
输出结果 ??????
描述,只计算数字类型的,日期啊,字符串之类的,不计算
df2.describe()
输出结果 ??????
A C D
count 4.0 4.0 4.0
mean 1.0 1.0 3.0
std 0.0 0.0 0.0
min 1.0 1.0 3.0
25% 1.0 1.0 3.0
50% 1.0 1.0 3.0
75% 1.0 1.0 3.0
max 1.0 1.0 3.0
输出结果 ??????
转置效果,行列转置
df2.T
输出结果 ??????
0 1 2
A 1 1 1
B 2013-01-02 00:00:00 2013-01-02 00:00:00 2013-01-02 00:00:00
C 1 1 1
D 3 3 3
E test train test
F foot foot foot
3
A 1
B 2013-01-02 00:00:00
C 1
D 3
E train
F foot
输出结果 ??????
排序
df2.sort_index
输出结果 ??????
<bound method DataFrame.sort_index of
A B C D E F
0 1.0 2013-01-02 1.0 3 test foot
1 1.0 2013-01-02 1.0 3 train foot
2 1.0 2013-01-02 1.0 3 test foot
3 1.0 2013-01-02 1.0 3 train foot>
输出结果 ??????
按列给出倒序排列
df2.sort_index(axis=1,ascending=False)
输出结果 ??????
F E D C B A
0 foot test 3 1.0 2013-01-02 1.0
1 foot train 3 1.0 2013-01-02 1.0
2 foot test 3 1.0 2013-01-02 1.0
3 foot train 3 1.0 2013-01-02 1.0
输出结果 ??????
按行给出倒序排列
df2.sort_index(axis=0,ascending=False)
输出结果 ??????
A B C D E F
3 1.0 2013-01-02 1.0 3 train foot
2 1.0 2013-01-02 1.0 3 test foot
1 1.0 2013-01-02 1.0 3 train foot
0 1.0 2013-01-02 1.0 3 test foot
输出结果 ??????
按照某列的值排序
df2.sort_values(by='E')
输出结果 ??????
A B C D E F
0 1.0 2013-01-02 1.0 3 test foot
2 1.0 2013-01-02 1.0 3 test foot
1 1.0 2013-01-02 1.0 3 train foot
3 1.0 2013-01-02 1.0 3 train foot
输出结果 ??????