提示:统计软件与数据分析Lesson1至Lesson3 补充知识点
要查看Python数据的基本信息,可以使用以下方法:
使用内置函数type()查看数据类型,例如:
x = 10
print(type(x))
输出结果为:
使用内置函数len()查看数据长度,例如:
my_list = [1, 2, 3, 4, 5]
print(len(my_list))
输出结果为:
5
使用内置函数dir()查看数据的所有属性和方法,例如:
my_string = "Hello, World!"
print(dir(my_string))
输出结果为:
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
变量名.shape ; 变量名.size
对于NumPy数组或Pandas DataFrame等数据结构,还可以使用相应的方法查看一些基本信息,例如:
import numpy as npmy_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(my_array.shape)
print(my_array.size)
输出结果为:
(3, 3)
9
变量名.shape ; 变量名.columns;变量名.info()
import pandas as pdmy_df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]})
print(my_df.shape)
print(my_df.columns)
print(my_df.info())
输出结果为:
(3, 3)Index(['A', 'B', 'C'], dtype='object')
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):# Column Non-Null Count Dtype
--- ------ -------------- -----0 A 3 non-null int641 B 3 non-null int642 C 3 non-null int64
dtypes: int64(3)
memory usage: 200.0 bytes
None
my_df.info()方法将打印出DataFrame对象的基本信息,以提供有关DataFrame对象的基本信息,例如列数、列名、非空值数、每列数据类型等。
plt.rcParams 是 matplotlib 库中的一个全局配置对象,可以用来设置全局的绘图参数。下面是一些常用的 plt.rcParams 属性:
可以设置的字体类型取决于系统中已安装的字体。以下是一些常见的可用字体类型:
‘serif’:有衬线字体,如 Times New Roman。
‘sans-serif’:无衬线字体,如 Arial。
‘cursive’:草书风格的字体,如 Comic Sans MS。
‘fantasy’:幻想风格的字体,如 Impact。
‘monospace’:等宽字体,如 Courier New。
如果要使用特定的字体类型,需要确保该字体已经被安装在系统中。可以通过以下方式查看已安装的字体类型:
import matplotlib.font_manager as fm
for font in fm.fontManager.ttflist:print(font.name)
输出结果为已安装的字体类型。根据输出结果可以选择使用合适的字体类型。
plt.rcParams[‘lines.linestyle’] 是用于设置线条样式的属性。可以设置的线条样式如下:
‘-’ 或 ‘solid’:实线。
‘–’ 或 ‘dashed’:破折线。
‘-.’ 或 ‘dashdot’:点划线。
‘:’ 或 ‘dotted’:虚线。
可以根据需要选择合适的线条样式,用于设置 matplotlib 图形中线条的样式。例如,以下代码将线条样式设置为 ‘–’:
import matplotlib.pyplot as pltplt.rcParams['lines.linestyle'] = '--'plt.plot([1, 2, 3], [4, 5, 6])
plt.show()
如果需要在 matplotlib 图形中使用中文或其他非英语语言,并且使用了含有负数的数据,则可能会出现负号乱码的情况。
此时可以将 plt.rcParams[‘axes.unicode_minus’] 设置为 False,避免负号乱码的问题。例如,以下代码将 plt.rcParams[‘axes.unicode_minus’] 设置为 False:
plt.rcParams['axes.unicode_minus'] = False
import matplotlib.pyplot as pltplt.rcParams['font.family'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['lines.linestyle'] = '--'x = [-1, 1, 2, 3]
y = [4, 5, 6, 7]plt.plot(x, y)
plt.title('负号不使用连字符')
plt.xlabel('x轴')
plt.ylabel('y轴')
plt.show()
可以通过设置这些属性来自定义 matplotlib 图像的外观和样式。需要注意的是,plt.rcParams 的属性是全局生效的,因此一般建议在程序开头设置一次即可
。
在 Python 中可以进行的均值检验方法有多种,常见的包括:
单样本 t 检验:用于检验一个样本的均值是否等于一个已知的总体均值。适用于总体方差未知的情况。可以使用 scipy.stats 模块中的 ttest_1samp 函数进行计算。
import scipy.stats as stats
import numpy as np# 创建一个样本数据
sample_data = np.array([1.2, 2.5, 0.8, 1.5, 2.1, 2.0, 1.9, 1.7, 1.4, 1.6])# 假设总体均值为 1.5
population_mean = 1.5# 进行均值检验
t_statistic, p_value = stats.ttest_1samp(sample_data, population_mean)# 输出 t 统计量和 p 值
print('t 统计量:', t_statistic)
print('p 值:', p_value)
独立样本 t 检验:用于比较两个独立样本的均值是否相等。适用于两个样本独立且总体方差相等的情况。可以使用 scipy.stats 模块中的 ttest_ind 函数进行计算。
import scipy.stats as stats
import numpy as np# 创建两个独立样本数据
sample_data1 = np.array([1.2, 2.5, 0.8, 1.5, 2.1])
sample_data2 = np.array([1.9, 1.7, 1.4, 1.6, 2.0])# 进行均值检验
t_statistic, p_value = stats.ttest_ind(sample_data1, sample_data2)# 输出 t 统计量和 p 值
print('t 统计量:', t_statistic)
print('p 值:', p_value)
配对样本 t 检验:用于比较两个相关样本的均值是否相等。适用于两个样本相关且总体方差相等的情况。可以使用 scipy.stats 模块中的 ttest_rel 函数进行计算。
import scipy.stats as stats
import numpy as np# 创建两个相关样本数据
sample_data1 = np.array([1.2, 2.5, 0.8, 1.5, 2.1])
sample_data2 = np.array([1.9, 1.7, 1.4, 1.6, 2.0])# 进行均值检验
t_statistic, p_value = stats.ttest_rel(sample_data1, sample_data2)# 输出 t 统计量和 p 值
print('t 统计量:', t_statistic)
print('p 值:', p_value)
方差分析(ANOVA):用于比较三个或三个以上独立样本的均值是否相等。适用于独立样本,但总体方差未必相等的情况。可以使用 scipy.stats 模块中的 f_oneway 函数进行计算。
单因素方差分析用于比较三个及以上组别之间的均值是否相等,适用于组别之间的样本独立、总体方差相等的情况。可以使用 scipy.stats 模块中的 f_oneway 函数进行计算。
import scipy.stats as stats
import numpy as np# 创建三个组别的样本数据
sample_data1 = np.array([1.2, 2.5, 0.8, 1.5, 2.1])
sample_data2 = np.array([1.9, 1.7, 1.4, 1.6, 2.0])
sample_data3 = np.array([0.9, 1.3, 1.6, 0.8, 1.1])# 进行方差分析
f_statistic, p_value = stats.f_oneway(sample_data1, sample_data2, sample_data3)# 输出 F 统计量和 p 值
print('F 统计量:', f_statistic)
print('p 值:', p_value)
双因素方差分析用于比较两个因素对样本均值的影响是否显著,适用于两个因素交互作用不显著、总体方差相等的情况。可以使用 statsmodels 模块中的 ols 函数进行计算。
import statsmodels.api as sm
import statsmodels.formula.api as smf
import pandas as pd# 创建一个数据集,包含两个因素和一个响应变量
df = pd.DataFrame({'factor1': ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D'],'factor2': ['X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y'],'response': [2.3, 3.1, 2.6, 3.3, 1.8, 2.0, 2.7, 3.2]})# 进行二因素方差分析
model = smf.ols('response ~ factor1 + factor2 + factor1:factor2', data=df).fit()
anova_table = sm.stats.anova_lm(model, typ=2)# 输出方差分析表
print(anova_table)
非参数方法:除了以上基于正态分布假设的方法外,还可以使用一些非参数方法,如 Mann-Whitney U 检验、Wilcoxon 符号秩检验等。这些方法不需要对总体分布做出任何假设,适用于数据分布未知或非正态分布的情况。
Mann-Whitney U 检验用于比较两个独立样本之间的中位数是否有显著差异,适用于样本不满足正态分布的情况。可以使用 scipy.stats 模块中的 mannwhitneyu 函数进行计算。
import scipy.stats as stats
import numpy as np# 创建两个独立样本
sample_data1 = np.array([1.2, 2.5, 0.8, 1.5, 2.1])
sample_data2 = np.array([1.9, 1.7, 1.4, 1.6, 2.0])# 进行 Mann-Whitney U 检验
u_statistic, p_value = stats.mannwhitneyu(sample_data1, sample_data2)# 输出检验结果
print('Mann-Whitney U 检验统计量:', u_statistic)
print('p 值:', p_value)
Wilcoxon 秩和检验用于比较两个相关样本之间的中位数是否有显著差异,适用于样本不满足正态分布的情况。可以使用 scipy.stats 模块中的 wilcoxon 函数进行计算。
import scipy.stats as stats
import numpy as np# 创建两个相关样本
sample_data1 = np.array([1.2, 2.5, 0.8, 1.5, 2.1])
sample_data2 = np.array([1.1, 2.0, 0.9, 1.4, 1.8])# 进行 Wilcoxon 秩和检验
w_statistic, p_value = stats.wilcoxon(sample_data1, sample_data2)# 输出检验结果
print('Wilcoxon 秩和检验统计量:', w_statistic)
print('p 值:', p_value)
不同的均值检验方法适用于不同的情景,需要根据实际问题和数据情况选择合适的方法。
在Python中,可以使用一对方括号 [] 来创建一个空列表或者包含元素的列表。以下是一些示例:
# 创建一个空列表
empty_list = []
print(empty_list)# 创建一个包含三个元素的列表
fruits = ['apple', 'banana', 'orange']
print(fruits)# 创建一个包含不同类型的元素的列表
mixed_list = ['apple', 1, 3.14, True]
print(mixed_list)
输出:
[]
['apple', 'banana', 'orange']
['apple', 1, 3.14, True]
在Python中,可以使用一对花括号 {} 来创建一个字典,或者使用内置的dict()函数来创建一个字典。字典由键-值对(key-value pairs)组成,每个键都唯一且不可变(通常是字符串或数字),对应一个值。以下是一些示例:
# 创建一个空字典
empty_dict = {}
print(empty_dict)# 创建一个包含三个键值对的字典
fruit_dict = {'apple': 2, 'banana': 3, 'orange': 1}
print(fruit_dict)# 通过 dict() 函数创建字典
person_dict = dict(name='Alice', age=25, city='New York')
print(person_dict)# 使用列表推导式创建字典
letters = ['a', 'b', 'c', 'd', 'e']
numbers = [1, 2, 3, 4, 5]
letter_number_dict = {letters[i]: numbers[i] for i in range(len(letters))}
print(letter_number_dict)
输出:
{}
{'apple': 2, 'banana': 3, 'orange': 1}
{'name': 'Alice', 'age': 25, 'city': 'New York'}
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
在上面的示例中,
Python 提取列表元素的方法有很多,以下是一些示例:
my_list = ['apple', 'banana', 'cherry']
print(my_list[0]) # 'apple'
print(my_list[1]) # 'banana'
print(my_list[2]) # 'cherry'
my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']
print(my_list[1:3]) # ['banana', 'cherry']
print(my_list[:3]) # ['apple', 'banana', 'cherry']
print(my_list[3:]) # ['date', 'elderberry']
print(my_list[1:5:2]) # ['banana', 'date']
my_list = ['apple', 'banana', 'cherry']
for item in my_list:print(item)
# 'apple'
# 'banana'
# 'cherry'
(2)循环索引提取
在 Python 中,可以通过循环遍历列表并使用索引值来提取元素。以下是一个示例:
my_list = ['apple', 'banana', 'cherry']
for i in range(len(my_list)):item = my_list[i]print(f"Index {i}: {item}")
输出:
Index 0: apple
Index 1: banana
Index 2: cherry
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_list = [x for x in my_list if x % 2 == 0]
print(even_list) # [2, 4, 6, 8, 10]
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_list = list(filter(lambda x: x % 2 == 0, my_list))
print(even_list) # [2, 4, 6, 8, 10]
**注意**
,如果索引超出了列表的范围,Python 会抛出 IndexError 异常。如果使用切片提取元素时,切片的结束位置超出了列表的范围,Python 会自动将结束位置设置为列表的长度。如果使用循环遍历列表时,可以使用 range() 函数来获取索引值。
append()
方法,该方法将元素添加到列表的末尾。以下是一个示例:fruits = ['apple', 'banana', 'orange']
fruits.append('kiwi')
print(fruits)
输出:
['apple', 'banana', 'orange', 'kiwi']
extend()
方法,可以将另一个列表的所有元素添加到当前列表中。以下是一个示例:# 使用 extend() 方法添加元素到列表中
fruits = ['apple', 'banana', 'orange']
fruits.extend(['kiwi', 'watermelon'])
print(fruits)
输出:
['apple', 'banana', 'orange', 'kiwi', 'watermelon']
insert()
方法将元素插入到列表的指定位置。例如:# 使用 insert() 方法将元素插入到列表的指定位置
fruits = ['apple', 'banana', 'orange']
fruits.insert(2, 'grape')
print(fruits)
输出:
['apple', 'banana', 'grape', 'orange', 'kiwi', 'watermelon']
除了 append()、extend() 和 insert() 方法之外,Python 列表还提供了其他方法用于向列表中添加元素:
list1 + list2
:将两个列表拼接在一起,返回一个新的列表。例如:# 拼接两个列表
list1 = [1, 2, 3]
list2 = [4, 5, 6]
new_list = list1 + list2
print(new_list)
输出:
[1, 2, 3, 4, 5, 6]
list1 += list2
或 1list1.extend(list2)1:将列表 list2 中的元素添加到 list1 中。例如:# 将列表中的元素添加到另一个列表
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1 += list2
print(list1)
输出:
[1, 2, 3, 4, 5, 6]
Python 中的循环语句有 for 循环和 while 循环,以下是一些示例:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:print(fruit)
输出:
apple
banana
cherry
在上面的代码中,我们使用 for 循环遍历列表 fruits 中的每个元素,并将其赋值给变量 fruit。在循环体中,我们使用 print() 函数输出每个水果。
count = 0
while count < 5:print(count)count += 1
输出:
0
1
2
3
4
在上面的代码中,我们使用 while 循环重复执行循环体中的语句,直到条件 count < 5 不再满足为止。在循环体中,我们使用 print() 函数输出变量 count 的值,并在每次循环结束前将其加 1。
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:if fruit == 'banana':breakprint(fruit)
输出:
apple
在上面的代码中,我们使用 break 语句在循环体中提前结束循环。当循环到水果 banana 时,break 语句被执行,循环立即结束,后面的水果不再被处理。
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:if fruit == 'banana':continueprint(fruit)
输出:
apple
cherry
在上面的代码中,我们使用 continue 语句跳过循环体中某个元素的处理。当循环到水果 banana 时,continue 语句被执行,后面的语句不再被执行,直接进入下一轮循环。