使用熊猫进行数据分析

熊猫 是用于数据分析的最流行的python库。它提供了高度优化的性能,后端源代码完全是用 C python .

null
We can analyze data in pandas with:

  1. Series
  2. DataFrames

系列:

系列 是熊猫中定义的一维(1-D)数组,可用于存储任何数据类型。

代码#1: 创作系列

# Program to create series
# Import Panda Library
import pandas as pd
# Create series with Data, and Index
a = pd.Series(Data, index = Index)


在这里 数据 可以是:

  1. A. 标量值 它可以是整型值,字符串
  2. A. Python字典 可以是键、值对
  3. A. 恩达雷

笔记 :默认情况下,索引从0、1、2、…(n-1)开始,其中n是数据的长度。 代码#2: 当数据包含标量值时

# Program to Create series with scalar values
# Numeric data
Data = [ 1 , 3 , 4 , 5 , 6 , 2 , 9 ]
# Creating series with default index values
s = pd.Series(Data)
# predefined index values
Index = [ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' ]
# Creating series with predefined index values
si = pd.Series(Data, Index)


输出 :

图片[1]-使用熊猫进行数据分析-yiteyi-C++库

Scalar Data with default Index

图片[2]-使用熊猫进行数据分析-yiteyi-C++库

Scalar Data with Index

代码#3: 当数据包含字典时

# Program to Create Dictionary series
dictionary = { 'a' : 1 , 'b' : 2 , 'c' : 3 , 'd' : 4 , 'e' : 5 }
# Creating series of Dictionary type
sd = pd.Series(dictionary)


输出 :

图片[3]-使用熊猫进行数据分析-yiteyi-C++库

Dictionary type data

代码#4: 当数据包含Ndarray时

# Program to Create ndarray series
# Defining 2darray
Data = [[ 2 , 3 , 4 ], [ 5 , 6 , 7 ]]
# Creating series of 2darray
snd = pd.Series(Data)


输出 :

图片[4]-使用熊猫进行数据分析-yiteyi-C++库

Data as Ndarray

数据帧:

数据帧 是熊猫中定义的二维(2-D)数据结构,由行和列组成。

代码#1: 数据帧的创建

# Program to Create DataFrame
# Import Library
import pandas as pd
# Create DataFrame with Data
a = pd.DataFrame(Data)


在这里,数据可以是:

  1. 一个或多个 字典
  2. 一个或多个 系列
  3. 2D numpy Ndaray

代码#2:当数据是字典时

# Program to Create Data Frame with two dictionaries
# Define Dictionary 1
dict1 = { 'a' : 1 , 'b' : 2 , 'c' : 3 , 'd' : 4 }
# Define Dictionary 2
dict2 = { 'a' : 5 , 'b' : 6 , 'c' : 7 , 'd' : 8 , 'e' : 9 }
# Define Data with dict1 and dict2
Data = { 'first' :dict1, 'second' :dict2}
# Create DataFrame
df = pd.DataFrame(Data)


输出 :

图片[5]-使用熊猫进行数据分析-yiteyi-C++库

DataFrame with two dictionaries

代码#3:当数据为系列时

# Program to create Dataframe of three series
import pandas as pd
# Define series 1
s1 = pd.Series([ 1 , 3 , 4 , 5 , 6 , 2 , 9 ])
# Define series 2
s2 = pd.Series([ 1.1 , 3.5 , 4.7 , 5.8 , 2.9 , 9.3 ])
# Define series 3
s3 = pd.Series([ 'a' , 'b' , 'c' , 'd' , 'e' ])
# Define Data
Data = { 'first' :s1, 'second' :s2, 'third' :s3}
# Create DataFrame
dfseries = pd.DataFrame(Data)


输出 :

图片[6]-使用熊猫进行数据分析-yiteyi-C++库

DataFrame with three series

代码#4:当数据是2D numpy Ndaray时 笔记 :创建二维数组的数据帧时必须保持一个约束条件–二维数组的尺寸必须相同。

# Program to create DataFrame from 2D array
# Import Library
import pandas as pd
# Define 2d array 1
d1 = [[ 2 , 3 , 4 ], [ 5 , 6 , 7 ]]
# Define 2d array 2
d2 = [[ 2 , 4 , 8 ], [ 1 , 3 , 9 ]]
# Define Data
Data = { 'first' : d1, 'second' : d2}
# Create DataFrame
df2d = pd.DataFrame(Data)


输出 :

图片[7]-使用熊猫进行数据分析-yiteyi-C++库

DataFrame with 2d ndarray

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享