数据统计中必备Python语言

目录

1.numpy库

 创建数组:

数组性质:

数组变形:

基本操作:

数组序列与切片:

注意:

补充:切片和列表作为索引时的本质区别

布尔索引:

注意:

离散程度:

分位数:

数组统计:

概率分布:

随机抽样:

协方差与相关系数:

2.subplot函数

基本绘图:

复杂图表:

3. pandas库

读取数据:

缺失值处理:

行列的选择:

注意:

补充loc与iloc的区别

补充:数据框和数组操作有什么异同

相同点:

不同点:

for循环

字符串格式化:

绘图:


1.numpy库

 创建数组:
import numpy as np

# 从列表创建一维数组
arr1d = np.array([1, 2, 3, 4, 5])

# 从嵌套列表创建二维数组
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# 从元组创建数组
arr_tuple = np.array((1, 3, 5, 7))
数组性质:
arr2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print(arr2d.shape)  # 输出:(3, 3),表示3行3列
print(arr2d.ndim)   # 输出:2,维度数
print(arr2d.dtype)  # 输出:int64,元素类型
print(arr2d.size)   # 输出:9,元素总数
数组变形:
x = np.array([1, 2, 3, 4, 5, 6])
print('beginning x:\n', x)
x_reshape = x.reshape((2, 3))   #两行三列
print('reshaped x:\n', x_reshape)

x_reshape[0, 0]  #输出:1
x_reshape[1, 2]  #输出:6

x_reshape.T  #转置
基本操作:
import numpy as np
arr = np.array([3, 1, 4, 2, 5])

#排序(返回新数组)
sorted_arr=np.sort(arr)  # 结果:[1, 2, 3, 4, 5]

获取排序后的索引
indices=np.argsort(arr)  # 结果:[1, 3, 0, 2, 4]

#最大值/最小值的索引
max_index=np.argmax(arr)  # 结果:4
min_index=np.argmin(arr)  # 结果:1

a=np.array([1, 2, 3])
b=np.array([4, 5, 6])

#加法
add_result=a+b #输出: [5 7 9]
#减法
sub_result=a-b #输出: [-3 -3 -3]
#乘法
mul_result=a*b #输出: [ 4 10 18]
#除法
div_result=a/b #输出: [0.25 0.4  0.5 ]

#累积求和
cumsum=np.cumsum(arr)  # 结果:[ 3,  4,  8, 10, 15]

#累积乘积
cumprod=np.cumprod(arr)  # 结果:[  3,   6,  24,  48, 240]

#均值
mean=np.mean(arr)

mean2=np.mean(axis=0) #按列计算均值
mean2=np.mean(axis=1) #按行计算均值


#中位数
median = np.median(arr)

#加权平均(weights参数指定权重)
weights = np.array([1, 1, 1, 1, 1, 1, 1, 1, 2])  #最后一个元素权重更高
weighted_mean = np.average(arr, weights=weights)

e=np.array([2, 3, 4])
#使用**进行幂运算
power_result_1 = e ** 2  #输出: [ 4  9 16]
#使用np.power()函数
power_result_2 = np.power(e, 2)  # 输出: [ 4  9 16]

f = np.array([1, 2, 3])
g = np.array([3, 2, 1])

#等于
equal_result = f == g  # 输出: [False True False]
#大于
greater_result = f > g  # 输出: [False False True]

j = np.array([True, False, True])
k = np.array([False, True, True])

#使用&进行逻辑与运算
logical_and_result_1 = j & k  # 输出: [False False True]
#使用 np.logical_and() 函数
logical_and_result_2 = np.logical_and(j, k)  # 输出: [False False True]

#使用 | 进行逻辑或运算
logical_or_result_1 = j | k  # 输出: [ True  True  True]
# 使用 np.logical_or() 函数
logical_or_result_2 = np.logical_or(j, k)  # 输出: [ True  True  True]

#使用 ~ 进行逻辑非运算
logical_not_result = ~j  # 输出: [False  True False]

#一维数组与标量运算
l = np.array([1, 2, 3])
scalar = 2
add_scalar_result = l + scalar  # 输出: [3 4 5]

#二维数组与一维数组运算
m = np.array([[1, 2, 3], [4, 5, 6]])
n = np.array([1, 0, 1])
add_array_result = m + n  
# 输出:
# [[2 2 4]
#  [5 5 7]]

#矩阵乘法
o=np.array([[1, 2], [3, 4]])
p=np.array([[5, 6], [7, 8]])

# 使用np.dot()函数
dot_result_1=np.dot(o, p)  
# 输出:
# [[19 22]
#  [43 50]]

# 使用@运算符
dot_result_2=o@p  
# 输出:
# [[19 22]
#  [43 50]]
数组序列与切片:
#创建数字序列
seq1 = np.linspace (0, 10, 11) 
#输出: array ([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])

#创建指定步长间隔的数字序列,若未指定,则默认步长为1
seq2 = np.arange(0, 10)
#输出:array ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),由于切片都是左闭右开原则,所以没有输出10。

#切片
"hello world"[3:6]  #'lo ' #实际只会输出第四到第六个字符,而不是第四个到第七个字符
#同理
"hello world"[slice(3,6)]

#切片获取子矩阵
A = np.array(np.arange (16)).reshape ((4, 4))
A[1,2]   #输出:6

#检索第二行和第四行
A[[1 ,3]] 
输出:
array ([[ 4, 5, 6, 7],
[12, 13, 14, 15]])

#检索第第一列和第三列
A[: ,[0 ,2]]

#检索第二行和第四行,第一列与第三列的子矩阵
A[[1 ,3] ,[0 ,2]]
#输出:
array ([4, 14])
注意:
#错误写法
A[[1,3] ,[0]] 
#numpy会将索引解释为坐标对
#即A[[1,3], [0,2]]表示选取坐标为(1,0)和(3,2)的元素,结果是[4, 14]

#正确写法
可采用分步写法
A[[1,3]][:, [0]]
#等价于
# 第一步:选行
rows = A[[1,3]] 
# 第二步:选列
result = rows[:, [0]]  #可得到一个2*1的矩阵,结果:[[4], [12]]

#也可以用np.ix_
idx = np.ix_([1,3], [0,2,3])
result = A[idx]

# 输出结果:
# [[ 4  6  7]
#  [12 14 15]]

#以上是列表索引,也可以用切片索引
#切片的基本语法是[start:stop:step],分别表示起始索引,结束索引以及步长,步长默认为1。
A[1:4:2 ,0:3:2]
#以1:4:2为例,从第2个元素开始,第5个元素结束,不包含第5个元素,步长为2,即隔一个元素取一个。也就是取第2,4行。
补充:切片列表作为索引时的本质区别
#列表索引
arr[[0,1], [1,0]]  # 结果:[1, 2]
#报错
arr[[0,1], [1,0,2]]

#切片索引
arr[0:2, 0:2]  # 提取第0、1行数据,第0、1列数据
# 输出:
# [[0, 1],
#  [2, 3]]

1.列表索引可以提取任意位置的元素

例如,A[[1,3], [0,2]]表示选取坐标为(1,0)和(3,2)的元素,结果是[4, 14]。这些坐标可以是离散的,没有规律的。而切片索引则适用于提取连续区域数据的场景。

2.切片索引更加灵活

在用列表进行索引的时候,必须保证行索引列表和列索引列表长度相同,否则就会报错。

3.列表索引得到的是一维数组,切片索引得到的是二维数组

4.切片索引返回的是原数组,列表索引返回的是原数组的副本,也就是和原数组不共享内存

#切片索引
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
sliced_view = arr[1:4]
sliced_view[0] = 99  
print(arr)  
# 输出:[ 1 99  3  4  5],原数组对应位置元素已被修改

#列表索引
arr = np.array([1, 2, 3, 4, 5])
list_index_result = arr[[1, 3]]
list_index_result[0] = 88  
print(arr)  
# 输出:[1 2 3 4 5],原数组未发生改变

所以相比于切片索引,列表索引在处理大型数组时,会占用更多的内存资源。

总结:

切片索引:

适合需要对原数组的某个连续区域进行快速访问和修改的场景,比如在数据分析中提取一段时间内的数据,或者在图像处理中对图像的某个区域进行批量处理。

列表索引:

适用于需要提取原数组中离散位置元素的场景,并且希望操作不会影响原数组的情况,比如在数据筛选中,根据特定条件选取不连续的元素。

布尔索引:
A = np.array(np.arange (16)).reshape ((4, 4))
A

#输出
array ([[ 0, 1, 2, 3],
        [ 4, 5, 6, 7],
        [ 8, 9, 10, 11],
        [12, 13, 14, 15]])

#获取A的行数,创建一个全为 False 的布尔数组。
keep_rows = np.zeros(A.shape[0], bool)
keep_rows
#输出
array ([False , False , False , False ])

keep_rows [[1 ,3]] = True
keep_rows
#输出
array ([False , True , False , True])

#True代表数值1,False代表数值0
np.all(keep_rows == np.array ([0,1,0,1]))   #np.all检查数组元素是否都为True


创建包含第二行和第四行、第一列、第三列和第四列的网格。
keep_cols = np.zeros(A.shape[1], bool)
keep_cols [[0, 2, 3]] = True
idx_bool = np.ix_(keep_rows,keep_cols)
A[idx_bool]
输出:
array ([[ 4, 6, 7],
        [12, 14, 15]])

#同理,可以在参数中混合一个列表和一个布尔数组
idx_mixed = np.ix_([1,3], keep_cols)
A[idx_mixed]
输出:
array ([[ 4, 6, 7],
        [12, 14, 15]])
注意:

尽管np.array([0,1,0,1])与keep_rows根据“==”相等,当时索引的是不同行集

A[np.array ([0,1,0,1])]

#输出:重复的一、二行
array ([[0, 1, 2, 3],
        [4, 5, 6, 7],
        [0, 1, 2, 3],
        [4, 5, 6, 7]])


A[keep_rows]
#输出:布尔值为TRUE的行集
array ([[ 4, 5, 6, 7],
        [12, 13, 14, 15]])
离散程度:
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
#方差
variance = np.var(arr)  # 结果:6.666...

#标准差
std_dev = np.std(arr)  # 结果:2.581...

#极差(最大值与最小值之差)
range_val = np.ptp(arr)  # 结果:8
分位数:
#25%、50%、75%分位数
q1 = np.percentile(arr, 25)  # 结果:3.0
q2 = np.percentile(arr, 50)  # 结果:5.0(等同于中位数)
q3 = np.percentile(arr, 75)  # 结果:7.0

#四分位距(IQR)
iqr = q3 - q1  # 结果:4.0
数组统计:
arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

#按行/列计算统计量(axis参数指定方向)
col_mean = np.mean(arr_2d, axis=0)  # 按列:[4. 5. 6.]
row_mean = np.mean(arr_2d, axis=1)  # 按行:[2. 5. 8.]

#统计满足条件的元素数量
count_greater_than_5 = np.sum(arr_2d > 5)  # 结果:4

#提取满足条件的元素并计算统计量
filtered_arr = arr_2d[arr_2d > 5]  # 结果:[6 7 8 9]
概率分布:
#正态分布(均值=0,标准差=1)
normal_data = np.random.normal(loc=0, scale=1, size=1000)

#设置随机种子,以得到相同的结果
rng = np.random.default_rng(1303)
print(rng.normal(scale=5, size=2))
rng2 = np.random.default_rng(1303)
print(rng2.normal(scale=5, size=2))

#均匀分布(范围[0, 1))
uniform_data = np.random.uniform(low=0, high=1, size=1000)

#泊松分布(λ=3)
poisson_data = np.random.poisson(lam=3, size=1000)
随机抽样:
#从已有数组中随机抽样
sample = np.random.choice(arr, size=5, replace=False)  # 无放回抽样

#打乱数组顺序(原地操作)
np.random.shuffle(arr)  # 例如:[3, 1, 5, 2, 4]
协方差与相关系数:
x = np.array([1, 2, 3, 4, 5])
y = np.array([5, 4, 6, 7, 8])

# 协方差矩阵(返回2x2矩阵)
cov_matrix = np.cov(x, y)
# 结果:
# [[ 2.5  3. ]
#  [ 3.   3.7]]

# 相关系数矩阵(皮尔逊相关系数)
corr_matrix = np.corrcoef(x, y)
# 结果:
# [[1.         0.98639392]
#  [0.98639392 1.        ]]

2.subplot函数

基本绘图:

from matplotlib.pyplot import subplots
fig,ax=subplots(figsize=(8,8))

#fig从(8,8)到(12,3)
fig.set_size_inches (12 ,3)

x=rng.standard normal(100)
y=rng.standard normal(100)
#折线图
ax.plot(x, y);
#散点图
ax.plot(x, y,'o'); #用‘o’绘制散点图
#用ax.scatter效果相同
ax.scatter(x, y, marker='o');

#添加 x 轴标签
ax.set_xlabel("这是 x 轴")

#添加 y 轴标签
ax.set_ylabel("这是 y 轴")

#添加标题
ax.set_title("X 与 Y 的图")

#显示图表
plt.show()

#绘制两行三列的子图
fig , axes = subplots(nrows=2,
ncols=3,
figsize =(15, 5))
#在第一行的第二列生成一个带’o’的散点图
axes[0,1].plot(x, y, 'o')
#第二行的第三列生成一个带'+'的散点图 
axes[1,2].scatter(x, y, marker='+')

#保存图像
fig.savefig("Figure.png", dpi=400)
fig.savefig("Figure.pdf", dpi=200);

#限制x轴范围在[-1,1]区间
axes[0,1].set_xlim([-1,1])
fig.savefig("Figure_updated.jpg")

复杂图表:
#等高线图绘制
fig, ax = subplots(figsize=(8, 8))
x = np.linspace(-np.pi, np.pi, 50)
y = x
f = np.multiply.outer(np.cos(y), 1 / (1 + x**2))
#将两个一维数组合成二维数组(外积)
#结果f是50×50的矩阵,每个元素 f[i,j] = cos(y[i]) * (1 / (1 + x[j]²))。
ax.contour(x, y, f);

#提高等高线分辨率
ax.contour(x, y, f, levels=45);

#绘制热图
ax.imshow(f);

3. pandas库

读取数据:
import pandas as pd

#Auto.csv用逗号分隔,直接用readcsv即可
Auto = pd.read_csv('Auto.csv')

#Auto.data用空白分隔,需加delim_whitespace=True whitespace=True
Auto = pd.read_csv('Auto.data', delim_whitespace=True)

#Auto.csv和Auto.data都是纯文本文件。在将数据加载到Python之前,使用文本编辑器或其他软件(如 Microsoft Excel)查看数据也可以。
缺失值处理:
#'horsepower'所有数据被解释为字符串
Auto['horsepower']
#通过唯一值得出原因,原因是“?”用来表示缺失值
np.unique(Auto['horsepower'])

#缺失值处理
Auto = pd.read_csv('Auto.data', 
                   na_values=['?'],       # 把 '?' 识别为缺失值(np.nan)
                   delim_whitespace=True) # 用空白分隔字段

#通过sum()方法验证,sum()会自动忽略 NaN,因此结果是有效数值的和。若未处理?,sum()会因字符串无法计算而报错。
Auto['horsepower'].sum()

#数据形状
Auto.shape  # 输出 (397, 9)
Auto_new = Auto.dropna()  # 删除包含缺失值的行
Auto_new.shape  # 输出 (392, 9)
行列的选择:
#查看列名
Auto.columns

#输出
Index(['mpg', 'cylinders', 'displacement', 'horsepower', 
       'weight', 'acceleration', 'year', 'origin', 'name'], 
      dtype='object')

#选择某行
Auto[:3]
idx_80 = Auto['year'] > 80
Auto[idx_80]
Auto.iloc [[3 ,4]]
Auto.loc['r1']

#选择某列
Auto[['mpg', 'horsepower']]

Auto.iloc[:, :3]  #选所有行,前 3 列(位置索引)
Auto.iloc[:,[0,2,3]]   #选取特定列
Auto.iloc [[3,4],[0 ,2 ,3]]  #选取特定行、列

Auto.loc[:, 'A']
cols = Auto.columns[:3]  #获取前 3 列的列名
Auto.loc[:, cols]        #选所有行,列名为 cols 的列

#同时选择行和列
Auto.loc['r1', 'A']


#设置索引
Auto_re = Auto.set_index('name ')
Auto_re.columns
#输出: 
Index (['mpg', 'cylinders', 'displacement', 'horsepower',
'weight', 'acceleration', 'year', 'origin'],
dtype='object')
#'name'不在输出中,因为已经被设置为索引
注意:

索引条目不必唯一:

选取"name"为ford galaxie 500的汽车

Auto_re.loc['ford galaxie 500', ['mpg', 'origin']]

补充loc与iloc的区别
import pandas as pd

df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [4, 5, 6],
    'C': [7, 8, 9]
}, index=['row1', 'row2', 'row3'])

#选择单行单列
#loc:通过标签选择,标签不存在时报错
print(df.loc['row1'])    # 选择索引为 'row1' 的行
print(df.loc[:, 'A'])    # 选择列 'A'

#iloc:通过位置选择,位置越界时报错
print(df.iloc[0])        # 选择第 0 行(即第一行)
print(df.iloc[:, 0])     # 选择第 0 列(即第一列)

#同时选中行和列
# loc
print(df.loc['row1', 'A'])  # 选择 'row1' 行和 'A' 列交叉处的值
print(df.loc[['row1', 'row3'], ['A', 'B']])  # 选择多行多列

# iloc
print(df.iloc[0, 0])        # 选择第 0 行第 0 列的值
print(df.iloc[[0, 2], [0, 1]])  # 选择多行多列

# loc:闭区间(包含起始和结束)
print(df.loc[0:2, 'A':'B'])  

   A  B
0  1  4
1  2  5
2  3  6

# iloc:左闭右开(包含起始,不包含结束)
print(df.iloc[0:2, 0:2])  # 包含第 0 行但不包含第 2 行

#输出
   A  B
0  1  4
1  2  5

#和列表,数组的切片是一样的
lst = [10, 20, 30]
print(lst[0:2])  #输出[10, 20]

arr = np.array([10, 20, 30])
print(arr[0:2])  #[10, 20]

#布尔索引
# loc:可直接用于布尔索引
mask = df['A'] > 1
print(df.loc[mask, 'B'])  #选择满足条件的行的 'B' 列

# iloc:需先将布尔条件转换为位置索引
mask = df['A'] > 1
print(df.iloc[mask.to_numpy().nonzero()[0], 1])

#当索引是整数时
df_int = pd.DataFrame({
    'A': [1, 2, 3]
}, index=[10, 20, 30])  #索引是整数标签,而非位置

#loc
print(df_int.loc[10:20])  #包含标签 10 和 20

#iloc
print(df_int.iloc[0:2])  #包含位置 0 和 1(对应标签 10 和 20)

#输出相同
    A
10  1
20  2
补充:数据框和数组操作有什么异同
相同点:
import numpy as np
import pandas as pd

# 创建数组和数据框
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
df = pd.DataFrame(arr, columns=['A', 'B', 'C'], index=['r1', 'r2', 'r3'])

#相同点1:基于位置索引选取元素
print(arr[1, 2])  # 输出6(第1行第2列)
print(df.iloc[1, 2])  # 输出6(第1行第2列)

#相同点2:切片操作
print(arr[0:2, 1:3])  # 输出: [[2 3], [5 6]]
print(df.iloc[0:2, 1:3])  # 输出对应两行两列的数据框

#相同点3:形状属性
print(arr.shape)  # 输出: (3, 3)
print(df.shape)  # 输出: (3, 3)
不同点:
#不同点1:数据类型
arr_mixed = np.array([[1, 'a'], [2, 'b']])
print(arr_mixed.dtype)  
#输出:<U11,也就是都转换最大长度为11的Unicode字符串,如果超过长度限制,则被截断

df_mixed = pd.DataFrame({'num': [1, 2], 'char': ['a', 'b']})
print(df_mixed['num'].dtype)  # 输出: int64
print(df_mixed['char'].dtype)  # 输出: object(字符串类型)

#补充:列表中整数和字符串共存
lst = [1, "apple"]
print(type(lst[0])) #输出: <class 'int'>
print(type(lst[1])) #输出: <class 'str'>

# 不同点2:行列标识
print(arr[0])  # 通过整数位置索引行
print(df.loc['r1'])  # 通过标签索引行
print(df['A'])  # 通过列名索引列

# 不同点3:行列操作
# 数组添加列
new_col = np.array([10, 11, 12]).reshape(-1, 1)
arr_new = np.hstack([arr, new_col])
print(arr_new)

#数据框添加列
df['D'] = [10, 11, 12]
print(df)

#数据框添加行
new_row = pd.DataFrame({'A': [13], 'B': [14], 'C': [15], 'D': [16]}, index=['r4'])
df = pd.concat([df, new_row])
print(df)

# 不同点4:数据处理
# 数组计算均值
print(np.mean(arr, axis=1))  # 按行计算均值

#数据框计算均值并添加统计列
df['mean_row'] = df.mean(axis=1)
print(df)

#数据框分组操作
df_group = pd.DataFrame({'group': ['A', 'A', 'B'], 'value': [1, 2, 3]})
print(df_group.groupby('group').sum())
#等价于
df_group.groupby('group')['value'].sum()
#输出
       value
group       
A          3
B          3

应用:

#创建一个数据框,包含年份大于 80 的汽车子集的重量和原产地
idx_80 = Auto_re['year'] > 80
Auto_re.loc[idx_80 , ['weight', 'origin']]
#或者
Auto_re.loc[lambda df: df['year'] > 80, ['weight', 'origin']]

#检索所有1980年后生产的、每加仑英里数大于 30 的汽车
Auto_re.loc[lambda df: (df['year '] > 80) & (df['mpg'] > 30),
['weight ', 'origin ']
]

#假设我们想要检索所有排量小于300的福特和达特桑汽车。我们使用str.contains()检查每个名称条目是否包含字符串 ford 或 datsun。
Auto_re.loc[lambda df: (df['displacement'] < 300)
& (df.index.str.contains('ford')
| df.index.str.contains('datsun')),
['weight','origin']
]
for循环
#输入
total = 0
for value in [3 ,2 ,19]:
total += value
print('Total is:{0}'.format(total))

#输出
Total is:24

total = 0
for value in [2 ,3 ,19]:
for weight in [3, 2, 1]:
total += value * weight
print('Total is:{0}'.format(total))

#输出
Total is:144

#计算加权平均值
total = 0
for value , weight in zip([2,3,19],
[0.2 ,0.3 ,0.5]):
total += weight * value
print('Weighted average is: {0}'.format(total))

#输出
Weighted average is: 10.8
字符串格式化:

(1)构建带缺失值的DataFrame:

rng = np.random.default_rng (1)
A = rng.standard_normal ((127 , 5))
M = rng.choice ([0, np.nan], p=[0.8 ,0.2] , size=A.shape)
A += M
D = pd.DataFrame(A, columns =['food',
                              'bar',
                              'pickle',
                              'snack',
                              'popcorn'])
D[:3]

输出:

(2)缺失值统计:

for col in D.columns:
    template = 'Column "{0}" has {1:.2%} missing values'  
    print(template.format(col, np.isnan(D[col]).mean()))  

输出: 

绘图:
#以下代码绘制散点图会报错
fig, ax = subplots(figsize=(8, 8))
ax.plot(horsepower, mpg, 'o');

#正确做法
#从DataFrame中取列
fig, ax = subplots(figsize=(8, 8))
ax.plot(Auto['horsepower'], Auto['mpg'], 'o');

#或者用DataFrame自带的.plot
ax = Auto.plot.scatter('horsepower', 'mpg');
ax.set_title('Horsepower vs. MPG')
#保存图片
fig = ax.figure  
fig.savefig('horsepower_mpg.png');

#绘制子图
fig, axes = subplots(ncols=3, figsize=(15, 5))  
#将散点图绘制在第2张子图中
Auto.plot.scatter('horsepower', 'mpg', ax=axes[1]);

#变量类型转换
cylinders(气缸数类别)原本是定量变量,但因为取值少,更适合当定性变量分析。
Auto.cylinders = pd.Series(Auto.cylinders, dtype='category')
Auto.cylinders.dtype

#绘制箱线图
fig, ax = subplots(figsize=(8, 8))
#以下代码用boxplot显示mpg(油耗)在不同 cylinders(气缸数类别)下的分布
Auto.boxplot('mpg', by='cylinders', ax=ax);

#绘制直方图
# 基础直方图
fig, ax = subplots(figsize=(8, 8))
Auto.hist('mpg', ax=ax);

# 改颜色、 bins(柱子数量)
fig, ax = subplots(figsize=(8, 8))
Auto.hist('mpg', color='red', bins=12, ax=ax);  
#柱子越多涵盖的范围越小,图更细,就能观察到更细节的分布

#绘制散点矩阵:用于观察多个变量的相关性
# 全部列的散点矩阵
pd.plotting.scatter_matrix(Auto);

# 选部分列
pd.plotting.scatter_matrix(Auto[['mpg', 'displacement', 'weight']]);

#describe()函数:可生成每列的统计摘要,包括最大/小值,平均值等等
# 多列汇总
Auto[['mpg', 'weight']].describe()

# 单列汇总
Auto['cylinders'].describe()
Auto['mpg'].describe()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值