NumPy 基本介绍:Python 中基于数组对象的科学计算库。支持大量维度数组和矩阵运算,NumPy 的核心是 ndarray 对象。
1.创建数组或矩阵
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import numpy as npdata1 = np.array([[1 , 2 , 3 ], [2 , 3 , 4 ]]) data2 = np.zeros(shape=(3 , 2 )) data3 = np.ones(shape=(3 , 2 )) data4 = np.empty(shape=(3 , 2 )) data5 = np.arange(1 , 10 , 2 ) data6 = np.linspace(0 , 10 , 5 ) data7 = np.random.rand(3 , 4 ) data8 = np.random.randint(2 , 5 , size=(2 , 3 ))
2.改变数组形状
1 2 3 reShapeData = np.arange(1 , 17 , 1 ) reShapeData = reShapeData.reshape((4 , 4 ))
3.ndarray 对象相关属性
.ndim
:维度
.shape
:形状
.size
:元素个数
.dtype
:数据类型
4.运算
1 2 3 4 5 6 7 8 9 10 array1 = np.array([[1 , 2 ], [2 , 1 ]]) array2 = np.array([[3 , 2 ], [2 , 3 ]]) print (array1 + array2)print (array1 * array2)""" [[4 4] [4 4]] [[3 4] [4 3]] """
5.统计操作
np.mean(arr, axis=None, dtype=None, out=None)
:平均值
axis:沿哪个轴线计算
dtype:返回的数据类型,默认是 float64
out:将结果存储在指定数组中
np.median(arr, axis=None, out=None)
:中位数
np.std(arr, axis=None, dtype=None, out=None)
:标准差
np.var(arr, axis=None, dtype=None, out=None)
:方差
np.min(arr, axis=None, out=None)
:最小值
np.max(arr, axis=None, out=None)
:最小值
np.sum(arr, axis=None, dtype=None, out=None)
:元素之和
np.prod(arr, axis=None, dtype=None, out=None)
:元素乘积
np.prod(arr, axis=None, dtype=None, out=None)
:累计和
6.切片
1 2 3 4 5 6 7 arr1 = np.array([1 , 2 , 3 , 4 , 5 ]) print (arr1[1 :4 ])arr2 = np.array([[1 , 2 , 3 ], [4 , 5 , 6 ], [7 , 8 , 9 ], [10 , 11 , 12 ]]) print (arr2[1 :3 ])print (arr2[:,1 :3 ])
7.堆叠
1 2 3 4 5 6 7 8 9 10 11 12 13 14 arr1 = np.array([[1 , 2 , 3 ], [4 , 5 , 6 ]]) arr2 = np.array([[4 , 5 , 6 ], [7 , 8 , 9 ]]) stacked_vertically = np.vstack((arr1, arr2)) stacked_horizontally = np.hstack((arr1, arr2)) print (stacked_vertically)print (stacked_horizontally)""" [[1 2 3] [4 5 6] [4 5 6] [7 8 9]] [[1 2 3 4 5 6] [4 5 6 7 8 9]] """
Pandas Series Pandas Series
类似表格中的一个列,可以保存任何数据类型。
1.定义 Series
:
1 2 3 4 5 6 7 8 9 10 data = np.array([1.2 , 2.0 , 3.5 ]) myseries1 = pd.Series( data, index=['x' , 'y' , 'z' ], name='my_series' , ) dict = {1 : "Google" , 2 : "Runoob" , 3 : "Wiki" }myseries2 = pd.Series(dict , index=[1 , 3 ])
2.切片和索引
1 2 3 4 5 6 7 print (myseries1[0 :2 ])myseries1['z' ] = 8.9 print (myseries1['x' :'y' ])del myseries1['z' ]
3.运算
1 2 3 4 5 6 result = series * 2 filtered_series = series[series > 2 ] result = np.sqrt(series)
4.属性和方法
.index
:获取索引
.values
:获取值数组
.describe()
:获取描述信息
.idxmax()
:最大值索引
.idxmin()
:最小值索引
.dtype
:数据类型
.shape
:形状
.size
:元素个数
.head()
:前几个元素,默认前 5 个
.tail()
:后几个元素,默认后 5 个
.sum()
:求和
.mean()
:平均值
.std()
:标准差
.min()
:最小值
.max()
:最大值
5.转换数据类型
1 2 series = series.astype('float64' )
DataFrame DataFrame
是 Pandas
中的另一个核心数据结构,用于表示二维表格型数据。
1.创建 DataFrame
,没有数据的地方会填充为 NaN
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 dfList = pd.DataFrame([[1 , 2 , 3 ], [4 , 5 , 6 ], [7 , 8 , 9 ]], columns=['Column1' , 'Column2' , 'Column3' ]) data = np.array([['Google' , 10 ], ['Runoob' , 12 ], ['Wiki' , 13 ]]) df = pd.DataFrame(data, columns=['Site' , 'Age' ]) print (df)dict = {'Site' :['Google' , 'Runoob' , 'Wiki' ], 'Age' :[10 , 12 , 13 ]}df2 = pd.DataFrame(dict , index=["day1" , "day2" , "day3" ]) print (df2)""" Site Age 0 Google 10 1 Runoob 12 2 Wiki 13 Site Age day1 Google 10 day2 Runoob 12 day3 Wiki 13 """
1 2 3 4 5 s1 = pd.Series(['Alice' , 'Bob' , 'Charlie' ]) s2 = pd.Series([25 , 30 , 35 ]) s3 = pd.Series(['New York' , 'Los Angeles' , 'Chicago' ]) df = pd.DataFrame({'Name' : s1, 'Age' : s2, 'City' : s3})
2.获取行
1 2 3 4 5 6 print (df2.loc["day2" ])print (df2.loc[["day2" , "day3" ]])print (df2.loc["day1" :"day3" ])
3.获取列
1 2 3 4 5 6 7 8 9 10 11 12 print (df2["Site" ])print (df2.loc[:, "Age" ])""" day1 Google day2 Runoob day3 Wiki Name: Site, dtype: object day1 10 day2 12 day3 13 Name: Age, dtype: int64 """
4.获取行列
1 2 3 4 5 6 7 print (df2.iloc[1 :3 , 1 :2 ])""" Age day2 12 day3 13 """
5.修改和新增列
1 2 df2["Sex" ] = ["Male" , "Female" , "Male" ]
6.修改和新增行
1 2 df2.loc["day2" ] = ["友塔" , 20 , "Female" ]
还可以使用 concat
添加:
1 2 3 4 5 6 7 8 9 10 new_row = pd.DataFrame([["Yotta" , 25 ]], columns=['Site' , 'Age' ], index=["day4" ]) df2 = pd.concat([df2, new_row], ignore_index=False ) print (df2)""" Site Age Sex day1 Google 10 Male day2 友塔 20 Female day3 Wiki 13 Male day4 Yotta 25 NaN """
7.删除行列
1 2 3 4 df2 = df2.drop(["Site" ], axis=1 ) df2 = df2.drop(["day2" ])
8.统计分析
.describe()
:统计摘要
.dtypes
:查看数据类型
.sum()
.mean()
.max()
9.索引操作
1 2 3 4 df_reset = df.reset_index(drop=True ) df_set = df.set_index('Column1' )
10.合并和分割
1 2 3 4 pd.concat([df1, df2], ignore_index=True ) pd.merge(df1, df2, on='Column1' )
1 2 3 4 df_pivot = df.pivot(index='Column1' , columns='Column2' , values='Column3' ) df_melt = df.melt(id_vars='Column1' , value_vars=['Column2' , 'Column3' ])
11.读取相关信息
head(n)
:读取前 n 行数据,为空则默认为 5
tail(n)
:读取后 n 行数据,为空则默认为 5,空行各个字段返回 NaN
info()
:表格基本信息
Pandas 格式文件 CSV to_string()
用于返回 DataFrame
类型的数据,如果不使用该函数,则输出结果为数据的前面 5 行和末尾 5 行,中间部分以 ...
代替。
1 2 3 import pandas as pddf = pd.read_csv('nba.csv' ) print (df.to_string())
也可以使用 to_csv()
将 DataFrame
转存为 CSV 文件:
JSON 1 2 3 import pandas as pddf = pd.read_json('sites.json' ) print (df.to_string())
如果有内嵌的 JSON 数据,可以使用 json_normalize()
方法完整展示出来:
1 2 3 4 5 6 7 8 import pandas as pdimport jsonwith open ('nested_list.json' ,'r' ) as f: data = json.loads(f.read()) df_nested_list = pd.json_normalize(data, record_path =['students' ]) print (df_nested_list)
数据清洗 1.清洗空值,使用 dropna()
方法:
axis:默认 0,表示逢空剔除整行,为 1 表示逢空剔除整列。
how:默认 any
,一行(或一列)有任何一个数据出现 NA 就去掉整行;如果设置为 how="all"
一行(或列)都是 NA 才去掉整行。
thresh:设置需要多少非空值的数据才可以保留下来的。
subset:设置想要检查的列。如果是多个列,可以使用列名的 list 作为参数。
inplace:如果设置 True,将计算得到的值直接覆盖之前的值并返回 None,修改的是源数据。
1 DataFrame.dropna(axis=0 , how='any' , thresh=None , subset=None , inplace=False )
2.也可以使用 fillna()
方法来替换一些空字段:
1 2 3 df['PID' ].fillna(12345 , inplace = True ) print (df.to_string())
3.可以通过包含空单元格的行或将列中所有单元格转换为相同格式的数据:
1 2 3 4 5 6 7 8 9 10 import pandas as pddata = { "Date" : ['2020/12/01' , '2020/12/02' , '20201226' ], "duration" : [50 , 40 , 45 ] } df = pd.DataFrame(data, index = ["day1" , "day2" , "day3" ]) df['Date' ] = pd.to_datetime(df['Date' ], format ='mixed' ) print (df.to_string())
4.可以使用 duplicated()
和 drop_duplicates()
清洗重复数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 import pandas as pdpersons = { "name" : ['Google' , 'Runoob' , 'Runoob' , 'Taobao' ], "age" : [50 , 40 , 40 , 23 ] } df = pd.DataFrame(persons) df.drop_duplicates(inplace = True ) print (df)""" name age 0 Google 50 1 Runoob 40 3 Taobao 23 """