pandas库简介和数据结构

pandas简介

pandas是一个强大的Python数据分析的工具包。是基于Numpy来构件的。

pandas提供快速、灵活和富有表现力的数据结构。

主要功能:

  • 具备对其功能的数据结构DataFrame、Series

  • 集成时间序列功能

  • 提供丰富的数学运算和操作

  • 灵活处理缺失数据

安装

pip install pandas

pandas数据结构-系列Series

Series是一种类似于一位数组的对象,由一组数据和一组与之相关的数据标签(索引)组成。

  • values:一组数据(ndarray类型)

  • index:相关的数据索引标签

pandas系列可以使用如下构造函数创建

pandas.Series( data, index, dtype, copy)

参数如下

编号 参数 描述
1 data 数据采取各种形式,如:ndarraylistconstants
2 index 索引值必须是唯一的和散列的,与数据的长度相同。 默认np.arange(n)如果没有索引被传递。
3 dtype dtype用于数据类型。如果没有,将推断数据类型
4 copy 复制数据,默认为false

series创建

1.通过列表或numpy数组创建,默认索引为0到N-1的整数型索引(隐式索引)

# 使用列表创建series
Series(data=[1,2,3,4])
​
# 通过设置index参数指定索引
s = Series(data=[1,2,3,4],index=["a","b","c","d"])
​
# 通过numpy创建
Series(data=np.random.randint(0,100,size=(3,)))

2.通过字典创建

# 通过字典创建series
s = Series(data={'a':1, 'b':2})

3.从标量创建一个系列

import pandas as pd
import numpy as np
s = pd.Series(5, index=[0, 1, 2, 3])

Series特性

Series支持数组的特性

  • 从ndarray创建Series:Series(arr)

  • 与标量运算:sr*2

  • 两个Series运算:sr1+sr2

  • 索引:sr[0], sr[[1,2,4]]

  • 切片:sr[0:2](切片依然是视图形式)

  • 通用函数:np.abs(sr)

  • 布尔值过滤:sr[sr>0]

s1 = Series(data=[1,2,3,4],index=["a","b","c","d"])
s2 = Series(data=[1,2,3,4],index=["a","b","e","d"])
s3 = s1+s2

统计函数

  • mean():求平均数

  • sum():求和

  • cumsum():累加

s = pd.Series({"a":1,"b":2,"c":3,"d":5,"e":7})
s.cumsum()

Series支持字典的特性(标签)

  • 从字典创建Series:Series(dic),

  • in运算:’a’ in sr、for x in sr

  • 键索引:sr['a'], sr[['a', 'b', 'd']]

  • 键切片:sr['a':'c']

  • 其他函数:get('a', default=0)等

# 点索引取值
s = pd.Series(0,index=["a","b","c","d","e"])
s.a
# 0
​
s1 = pd.Series({'a':1,'b':2})
s1.a  # 1
s1[0]  # 1
​
s1*2
a 2
b 4

Series索引

1.具有位置的系列访问数据

系列中的数据可以使用类似于访问ndarray中的数据来访问

s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
# 检索第一个元素
print s[0]
# 检索系列中的前三个元素
print s[:3]
# 检索最后三个元素
print s[-3:]

2.使用标签检索数据(索引)

一个系列就像一个固定大小的字典,可以通过索引标签获取和设置值。

import pandas as pd
s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
​
# 使用索引标签值检索单个元素
print(s["a"])
​
# 使用索引标签值列表检索多个元素
print(s[['a','c','d']])
​
# 如果不包含标签,则会出现异常
print s['f']
# keyError:"f"

Series数据对齐

pandas在运算时,会按索引进行对齐然后计算。如果存在不同的索引,则结果的索引是两个操作数索引的并集。

  • 在运算中自动对齐不同索引的数据

  • 如果索引不对应,则补NaN

s1 = Series(data=[1,2,3,4],index=["a","b","c","d"])
s2 = Series(data=[1,2,3,4],index=["a","b","e","d"])
s3 = s1+s2
# 输出
a    2.0
b    4.0
c    NaN
d    8.0
e    NaN
dtype: float64

当索引没有对应的值,可能会出现缺失数据显示NaN(not a number)的情况。

s3.isnull()  # 为空检测
s3.notnull()  # 非空检测
s3[[True,True,False,True,False]]  # 如果将布尔值作为Series的索引,则只会保留True对应的元素的值
s3[s3.notnull()]  # 直接可以返回没有缺失的数据
# 输出:
a    2.0
b    4.0
d    8.0
dtype: float64

pandas数据结构-数据帧DataFrame

数据帧(DataFrame)是二维数据结构,即数据以行和列的表格方式排列。

数据帧(DataFrame)的功能特点:

  • 潜在的列是不同的类型

  • 大小可变

  • 标记轴(行和列)

  • 可以对行和列执行算术运算

pandas中的DataFrame可以使用以下构造函数创建

pandas.DataFrame( data, index, columns, dtype, copy)

参数如下:

编号 参数 描述
1 data 数据采取各种形式,如:ndarrayseriesmaplistsdictconstant和另一个DataFrame
2 index 对于行标签,要用于结果帧的索引是可选缺省值np.arrange(n),如果没有传递索引值。
3 columns 对于列标签,可选的默认语法是 - np.arange(n)。 这只有在没有索引传递的情况下才是这样。
4 dtype 每列的数据类型。
5 copy 如果默认值为False,则此命令(或任何它)用于复制数据。

创建DataFrame

Pandas数据帧(DataFrame)可以使用各种输入创建,如 -

  • 列表

  • 字典

  • 系列

  • Numpy ndarrays

  • 另一个数据帧(DataFrame)

# 创建一个空数据帧
import pandas as pd
df = pd.DataFrame()
​
# 从列表创建DataFrame
data = [1,2,3,4,5]
df = pd.DataFrame(data)

从ndarrays/Lists的字典来创建DataFrame

所有的ndarrays必须具有相同的长度。如果传递了索引(index),则索引的长度应等于数组的长度。

如果没有传递索引,则默认情况下,索引将为range(n),其中n为数组长度。

import pandas as pd
data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data)
​
# 使用数组创建一个索引的数据帧
data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data, index=['rank1','rank2','rank3','rank4'])

从系列的字典来创建DataFrame

字典的系列可以传递以形成一个DataFrame。 所得到的索引是通过的所有系列索引的并集。

import pandas as pd
​
d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
      'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
​
df = pd.DataFrame(d)
print(df)

DataFrame数据查询

列的相关操作

列选择

从数据帧(DataFrame)中选择一列

import pandas as pd
​
d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
      'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
​
df = pd.DataFrame(d)
df["one"]
​
输出
a     1.0
b     2.0
c     3.0
d     NaN
Name: one, dtype: float64

列添加

通过向现有数据框添加一个新列

print ("Adding a new column by passing as Series:")
df['three']=pd.Series([10,20,30],index=['a','b','c'])
print(df)
​
输出
Adding a new column by passing as Series:
     one   two   three
a    1.0    1    10.0
b    2.0    2    20.0
c    3.0    3    30.0
d    NaN    4    NaN

列删除

列可以删除或弹出

import pandas as pd
​
d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']), 
     'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd']), 
     'three' : pd.Series([10,20,30], index=['a','b','c'])}
​
df = pd.DataFrame(d)
print ("Deleting the first column using DEL function:")
del df['one']

行的相关操作

行的标签选择

通过将行标签传递给loc()函数来选择行

import pandas as pd
​
d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']), 
     'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
​
df = pd.DataFrame(d)
print(df.loc['b'])
​
输出
one 2.0
two 2.0
Name: b, dtype: float64

行的整数位置选择

可以通过将整数位置传递给iloc()函数来选择行

import pandas as pd
​
d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
     'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
​
df = pd.DataFrame(d)
print(df.iloc[2])
​
输出
one   3.0
two   3.0
Name: c, dtype: float64

行切片

可以使用:运算符选择多行

import pandas as pd
​
d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']), 
    'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
​
df = pd.DataFrame(d)
print(df[2:4])
​
输出
      one    two
c     3.0     3
d     NaN     4

添加行

使用append()函数将新行添加到DataFrame, 此功能将附加行结束

import pandas as pd
​
df = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b'])
df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b'])
​
df = df.append(df2)
print(df)
执行上面示例代码,得到以下结果 -

   a  b
0  1  2
1  3  4
0  5  6
1  7  8

删除行

使用索引标签从DataFrame中删除或删除行。

import pandas as pd
​
df = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b'])
df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b'])
​
df = df.append(df2)
​
# Drop rows with label 0
df = df.drop(0)
​
print(df)

执行上面示例代码,得到以下结果 -

  a b
1 3 4
1 7 8

 

猜你喜欢

转载自www.cnblogs.com/ryxiong-blog/p/11347689.html
今日推荐