Python技术迷

Pandas 教程-Pandas NumPy

整理: python架构师

Numerical Python(Numpy)被定义为一个用于执行各种数值计算和处理多维和单维数组元素的Python包。使用Numpy数组进行的计算比普通的Python数组更快。 这个包是由Travis Oliphant于2005年创建的,通过将祖先模块Numeric的功能添加到另一个模块Numarray中而创建的。它还能够处理大量数据,并且在矩阵乘法和数据重塑方面非常方便。 NumPy主要是用C语言编写的,它是Python的一个扩展模块。 Pandas是建立在NumPy数组之上的,因此NumPy帮助我们更有效地使用Pandas。 创建数组 数组的主要任务是在单个变量中存储多个值。它定义了可以在NumPy中轻松处理的多维数组,如下面的示例所示: 示例
# import the "array" for demonstrating array operations  import array  # initializing an array with array values and signed integers  arr = array.array('l', [2, 4, 6, 8, 10, 12])   # print the original array  print ("New created array: ",end="")  for l in range (0,5):  print (arr[l], end=" ")  print ("\r")
输出:
New created array: 2 4 6 8 10
专属福利 
👉点击领取:最全Python资料合集

布尔索引

布尔索引被定义为NumPy的一个重要工具,经常在Pandas中使用。其主要任务是使用DataFrame中的实际数据值。我们可以通过不同的方式在布尔索引中过滤数据,如下所示:
  • 使用布尔索引访问DataFrame。
  • 将布尔掩码应用于DataFrame。
  • 基于列值掩码数据。
  • 基于索引值掩码数据。
示例1 此示例演示如何使用布尔索引访问DataFrame:
# importing pandas as pd  import pandas as pd  # dictionary of lists   dict = {'name':["Smith", "William", "Phill", "Parker"],           'age': ["28", "39", "34", "36"]}   info = pd.DataFrame(dict, index = [True, True, False, True])   print(info)
输出:
name    ageTrue     Smith    28True   William   39False    Phill   34True    Parker    36
示例2 此示例演示如何使用.loc[]通过布尔索引访问DataFrame:
# importing pandas as pd  import pandas as pd  # dictionary of lists   dict = {'name':["Smith", "William", "Phill", "Parker"],           'age': ["28", "39", "34", "36"]}   info = pd.DataFrame(dict, index = [True, True, False, True])   # accessing a dataframe using .loc[] function    print(info.loc[True])
输出:
name    ageTrue     Smith    28True   William    39True    Parker    36

重塑数组

重塑数组用于在不更改数据的情况下重塑数组。 语法
numpy.reshape(a, newshape, order='C')
参数
  • a:定义要重塑的数组。
  • newshape:定义应与原始形状兼容的新形状。对于整数值,结果将是该长度的1-D数组。一个形状维度可以是-1。
  • order:这是一个可选参数,它通过使用索引顺序读取元素,并使用索引顺序将元素放入重塑后的数组。
返回: 返回重塑后的数组。 示例
import numpy as np  arr = np.arange(16)  print("The Original array is: \n", arr)  # shape array with 2 rows and 8 columns  arr = np.arange(16).reshape(2, 8)  print("\nreshapedarray: \n", arr)  # shape array with 2 rows and 8 columns  arr = np.arange(16).reshape(8 ,2)  print("\nreshaped array: \n", arr)
输出:
The Original array is:  [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15]reshaped array:  [[ 0  1  2  3  4  5  6  7][ 8  9 10 11 12 13 14 15]]reshaped array:  [[ 0  1][ 2  3][ 4  5][ 6  7][ 8  9] [10 11] [12 13] [14 15]]



1
 
热门推荐