参考博客 官方文档

导入pandas

import pandas as pd

Pandas是一个强大的分析结构化数据的工具集;它的使用基础是Numpy(提供高性能的矩阵运算);用于数据挖掘和数据分析,同时也提供数据清洗功能。Pandas 的主要数据结构是 Series(一维数据)与 DataFrame(二维数据),这两种数据结构足以处理金融、统计、社会科学、工程等领域里的大多数典型用例。

Series

pd.Series(self, data=None, index=None, dtype=None, name=None, copy=False, fastpath=False)

index为可选参数,若不填写则默认index从0开始;若填写则index长度应该与data长度相等。
它是一种类似于一维数组的对象,是由一组数据(各种NumPy数据类型)以及一组与之相关的数据标签(即索引)组成。仅由一组数据也可产生简单的Series对象。
示例1:

import pandas as pd
import numpy as np
s = pd.Series([1, 3, 5, np.nan, 6, 8])
print(s)
输出:
    0    1.0
    1    3.0
    2    5.0
    3    NaN
    4    6.0
    5    8.0
    dtype: float64

示例2(加入index):

s = pd.Series([1,2,3,4,5],index=['a','b','c','d','e'])
print(s)
输出:
a    1
b    2
c    3
d    4
e    5
dtype: int64

示例3(字典形式传入):

s = pd.Series({'a':1,'b':2,'c':3})
print(s)
输出:
a    1
b    2
c    3
dtype: int64

示例4(全一个值):

s =pd.Series('ex',index=range(4))
print(s)
输出:
0    ex
1    ex
2    ex
3    ex
dtype: object

Series对象还有以下方法

dropna() # 过滤掉值为NaN的行
fillna() # 填充缺失数据
isnull() # 返回布尔数组,缺失值对应为True
notnull() # 返回布尔数组,缺失值对应为False

在pandas当中使用整数索引取值是优先以标签解释的(就是index的值),而不是下标,即s[1]的1是index值,不是下标。

DataFrame

DataFrame是Pandas中的一个表格型的数据结构,包含有一组有序的列,每列可以是不同的值类型(数值、字符串、布尔型等),DataFrame即有行索引也有列索引,可以被看做是由Series组成的字典。
示例1(通过字典创建DataFrame)

df=pd.DataFrame({'one':[1,2,3,4],'two':[4,3,2,1]},index=[list("abcd")])
print(df)
输出:
   one  two
a    1    4
b    2    3
c    3    2
d    4    1

字典的key就是列索引,行索引和series一致
示例2(用含日期时间索引与标签的 NumPy 数组生成 DataFrame):

import pandas as pd
import numpy as np
s = pd.Series([1, 3, 5, np.nan, 6, 8])
print(s)
dates = pd.date_range('20200528', periods=6)
print(dates)
df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))
print(df)
输出:
DatetimeIndex(['2020-05-28', '2020-05-29', '2020-05-30', '2020-05-31',
               '2020-06-01', '2020-06-02'],dtype='datetime64[ns]', freq='D')  

                   A         B         C         D
2020-05-28  0.855412  0.579027 -0.230115  0.219510
2020-05-29 -1.326889 -2.332480  0.903092 -0.434896
2020-05-30  0.261738 -0.241283  0.366975 -0.663830
2020-05-31  0.529805 -0.476377  0.612251  0.298802
2020-06-01  0.954291 -0.353668  1.025417 -0.102539
2020-06-02  0.304185 -1.111570 -0.988662 -0.906860

DataFrame常用方法:
index 获取行索引
columns 获取列索引
T 转置
values 获取值
describe() 获取快速统计
DataFrame切片
方法1:两个中括号,先取列再取行。

print(df['one'][0:2])
输出:
a    1
b    2  

方法2(推荐):使用loc(标签)/iloc(下标)属性,一个中括号,逗号隔开,先取行再取列。
df.loc

#df.loc[index, column_name]#知道列名字
df=pd.DataFrame(np.random.randn(5,3),columns=['1st','2st','3st'])
print("df:\n",df)
print("切片:\n",df.loc[0:2,'1st'])
输出
df:
         1st       2st       3st
0 -0.423567 -1.641365 -0.964554
1  2.182152  1.946627  1.567575
2  1.460775  0.241103 -0.213155
3 -0.174908 -0.838250 -0.601795
4 -0.223915  0.912240  0.764790
切片:
0   -0.423567
1    2.182152
2    1.460775
Name: 1st, dtype: float64

df.iloc

#df.iloc[row_index, column_index]
print(df.iloc[[1,2],[1,2]])
输出:
        2st       3st
1  1.061422 -1.293969
2  0.850033 -0.096409

DataFrame可以由不同数据类型组成

df2 = pd.DataFrame({'A': 1.,
                     'B': pd.Timestamp('20200529'),
                     '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 2020-05-29  1.0  3   test  foo
1  1.0 2020-05-29  1.0  3  train  foo
2  1.0 2020-05-29  1.0  3   test  foo
3  1.0 2020-05-29  1.0  3  train  foo

df.to_numpy()

调用 DataFrame.to_numpy() 时,Pandas 查找支持 DataFrame 里所有数据类型的 NumPy 数据类型。还有一种数据类型是 object,可以把 DataFrame 列里的值强制转换为 Python 对象。

dftonp=df2.to_numpy()
print(dftonp)
输出:
[[1.0 Timestamp('2020-05-29 00:00:00') 1.0 3 'test' 'foo']
 [1.0 Timestamp('2020-05-29 00:00:00') 1.0 3 'train' 'foo']
 [1.0 Timestamp('2020-05-29 00:00:00') 1.0 3 'test' 'foo']
 [1.0 Timestamp('2020-05-29 00:00:00') 1.0 3 'train' 'foo']]

df.describe()
用于查看数据的统计摘要
print(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

读写文件

csv

pd.read_csv('xxx.csv')
df.to_csv('xxx.csv')

excel

pd.read_excel('foo.xlsx', 'Sheet1', index_col=None, na_values=['NA'])  
df.to_excel('foo.xlsx', sheet_name='Sheet1')

本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!

numpy 上一篇
matplotlib 下一篇