1. Pandas系列 - 基本数据结构

时间:2022-07-24
本文章向大家介绍1. Pandas系列 - 基本数据结构,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

从这一篇文章开始,想要跟大家一起探讨关于数据科学最重要的工具了,就是Python提供了 Numpy 和 Pandas,咱们先从Pandas开始,走上数据分析高手之路hhhh

先看下本文文章概览:

  • 一、pandas.Series
    • 数组
    • 字典
    • 标量值 or 常数
  • 二、pandas.DataFrame
    • 创建DataFrame
    • 列选择
    • 列添加
    • 列删除 pop/del
    • 行选择,添加和删除
    • 行切片
  • 三、pandas.Panel()
    • 创建面板
    • 从面板中选择数据

系列(Series)是能够保存任何类型的数据(整数,字符串,浮点数,Python对象等)的一维标记数组。轴标签统称为索引

一、pandas.Series

构造函数

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

编号

参数

描述

1

data

数据采取各种形式,如:ndarray,list,constants

2

index

索引值必须是唯一的和散列的,与数据的长度相同 默认np.arange(n)如果没有索引被传递

3

dtype

dtype用于数据类型 如果没有,将推断数据类型

4

copy

复制数据,默认为false

构成一个Series的输入有:

  • 数组
  • 字典
  • 标量值
  • 常数

数组

#import the pandas library and aliasing as pd
import pandas as pd
import numpy as np
data = np.array(['a','b','c','d'])
s = pd.Series(data,index=[100,101,102,103])
print s
100  a
101  b
102  c
103  d
dtype: object

字典

#import the pandas library and aliasing as pd
import pandas as pd
import numpy as np
data = {'a' : 0., 'b' : 1., 'c' : 2.}
s = pd.Series(data,index=['b','c','d','a'])
print s
b 1.0
c 2.0
d NaN
a 0.0
dtype: float64

标量值 or 常数

#import the pandas library and aliasing as pd
import pandas as pd
import numpy as np
s = pd.Series(5, index=[0, 1, 2, 3])
print s
0  5
1  5
2  5
3  5
dtype: int64

二、pandas.DataFrame

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

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

  • 潜在的列是不同的类型
  • 大小可变
  • 标记轴(行和列)
  • 可以对行和列执行算术运算

构造函数:

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

编号

参数

描述

1

data

数据采取各种形式,如:ndarray,series,map,lists,dict,constant和另一个DataFrame。

2

index

对于行标签,要用于结果帧的索引是可选缺省值np.arrange(n),如果没有传递索引值。

3

columns

对于列标签,可选的默认语法是 - np.arange(n)。这只有在没有索引传递的情况下才是这样。

4

dtype

每列的数据类型。

5

copy

如果默认值为False,则此命令(或任何它)用于复制数据。

创建DataFrame

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

  • 列表
  • 字典
  • 系列(Series)
  • Numpy ndarrays
  • 另一个数据帧(DataFrame)

列表

import pandas as pd
data = [1,2,3,4,5]
df = pd.DataFrame(data)
print df

res:

     0
0    1
1    2
2    3
3    4
4    5
import pandas as pd
data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]
df = pd.DataFrame(data, index=['first', 'second'])
print df

res:

    a    b      c
0   1   2     NaN
1   5   10   20.0

字典

import pandas as pd
data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data, index=['rank1','rank2','rank3','rank4'])
print df

res:

         Age    Name
rank1    28      Tom
rank2    34     Jack
rank3    29    Steve
rank4    42    Ricky

系列(Series)

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

res:

      one    two
a     1.0    1
b     2.0    2
c     3.0    3
d     NaN    4

列选择

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 ['one']

列添加

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)

# Adding a new column to an existing DataFrame object with column label by passing new series

print ("Adding a new column by passing as Series:")
df['three']=pd.Series([10,20,30],index=['a','b','c'])
print df

print ("Adding a new column using the existing columns in DataFrame:")
df['four']=df['one']+df['three']

print df

列删除 pop/del

# Using the previous DataFrame, we will delete a column
# using del function
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 ("Our dataframe is:")
print df

# using del function
print ("Deleting the first column using DEL function:")
del df['one']
print df

# using pop function
print ("Deleting another column using POP function:")
df.pop('two')
print df

行选择,添加和删除

标签选择 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']

按整数位置选择 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]

行切片

附加行 append

使用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

删除行 drop

使用索引标签从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

三、pandas.Panel()

面板(Panel)是3D容器的数据

3轴(axis)这个名称旨在给出描述涉及面板数据的操作的一些语义

details

items

axis 0,每个项目对应于内部包含的数据帧(DataFrame)

major_axis

axis 1,它是每个数据帧(DataFrame)的索引(行)

minor_axis

axis 2,它是每个数据帧(DataFrame)的列

pandas.Panel(data, items, major_axis, minor_axis, dtype, copy)

构造函数的参数如下:

参数

描述

data

数据采取各种形式,如:ndarray,series,map,lists,dict,constant和另一个数据帧(DataFrame)

items

axis=0

major_axis

axis=1

minor_axis

axis=2

dtype

每列的数据类型

copy

复制数据,默认 - false

创建面板

可以使用多种方式创建面板

  • 从ndarrays创建
  • 从DataFrames的dict创建

从3D ndarray创建

# creating an empty panel
import pandas as pd
import numpy as np

data = np.random.rand(2,4,5)
p = pd.Panel(data)
print data
print p

res:

>>> print data
[[[0.79346549 0.22729079 0.94261176 0.67379434 0.18751374]
  [0.14514546 0.50550601 0.32767807 0.45882726 0.04787695]
  [0.64748544 0.2019516  0.38334503 0.61874107 0.68800838]
  [0.39880845 0.41415895 0.69383131 0.71159435 0.06160828]]

 [[0.97102379 0.69454937 0.54629548 0.83072134 0.53068539]
  [0.82441684 0.5882186  0.69936055 0.0924247  0.12300041]
  [0.30401452 0.12971053 0.90511636 0.17855185 0.05474733]
  [0.04730471 0.03639553 0.74632198 0.85193736 0.64864719]]]
>>> print p
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 4 (major_axis) x 5 (minor_axis)
Items axis: 0 to 1
Major_axis axis: 0 to 3
Minor_axis axis: 0 to 4

从DataFrame对象的dict创建面板

#creating an empty panel
import pandas as pd
import numpy as np

data = {'Item1' : pd.DataFrame(np.random.randn(4, 3)), 
        'Item2' : pd.DataFrame(np.random.randn(4, 2))}
p = pd.Panel(data)
print data
print p

res:

{'Item2':           
          0         1
0  0.009730  2.263936
1 -1.008878  1.083319
2  0.288527  0.234344
3 -0.426486  0.286741, 
'Item1':           
      0         1         2
0 -2.149956  1.696135 -0.256530
1 -1.063944 -1.033069  0.653613
2 -0.645782 -0.097129  1.034462
3 -0.041070  0.104719  0.577797}

>>> print p
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 4 (major_axis) x 3 (minor_axis)
Items axis: Item1 to Item2
Major_axis axis: 0 to 3
Minor_axis axis: 0 to 2

创建一个空面板

#creating an empty panel
import pandas as pd
p = pd.Panel()
print p

res:

<class 'pandas.core.panel.Panel'>
Dimensions: 0 (items) x 0 (major_axis) x 0 (minor_axis)
Items axis: None
Major_axis axis: None
Minor_axis axis: None

从面板中选择数据

要从面板中选择数据,可以使用以下方式

  • Items
  • Major_axis
  • Minor_axis
import pandas as pd
import numpy as np
data = {'Item1' : pd.DataFrame(np.arange(12).reshape(4, 3)), 
        'Item2' : pd.DataFrame(np.arange(8).reshape(4, 2))}
p = pd.Panel(data)
print data
# 使用Item
print p['Item1']
# 使用Major_axis
print p.major_xs(1)
# 使用Minor_axis
print p.minor_xs(1)
data:
{'Item2':    
   0  1
0  0  1
1  2  3
2  4  5
3  6  7, 
'Item1':    
   0   1   2
0  0   1   2
1  3   4   5
2  6   7   8
3  9  10  11}

>>> # 使用Item
... print p['Item1']
   0   1   2
0  0   1   2
1  3   4   5
2  6   7   8
3  9  10  11
>>> # 使用Major_axis
... print p.major_xs(1)
   Item1  Item2
0      3    2.0
1      4    3.0
2      5    NaN
>>> # 使用Minor_axis
... print p.minor_xs(1)
   Item1  Item2
0      1    1.0
1      4    3.0
2      7    5.0
3     10    7.0

后面呢估计会写点儿关于Pandas的常用操作,一起期待~

作者:Johngo

配图:Pexels