Introduction to Data Science in Python 是 DataCamp 中 Python Programmer Career Track 的第一门课程。
本节课可以学习到:
- 学写 Python 代码
- 从表格中加载数据
- 可视化数据
目录
Import
# Import a module import matplotlib # Import a module with an alias import matplotlib.pyplot as plt # From Import from matplotlib import pyplot as plt
Variable
Rule for variable names
字母起始,使用字母、数字、下划线,大小写敏感
Float and String
float:整数或小数
string:文本字符串
Function
函数是一种行为

代码中函数的作用
import pandas as pd from matplotlib import pyplot as plt # pd.read_csv() 将csv文件转换为Python表格 df = pd.read_csv('letter_frequency.csv') # plt.plot() 将数据转换为折线图 plt.plot(df.letter_index, df.frequency, label='Ransom') # plt.show() 在新窗口显示图 plt.show()
解剖函数调用
函数调用以模块名开始,点连接函数名;参数包含在括号中,用逗号分隔
按照顺序填入的必填参数为位置参数(Positional Arguments)
在位置参数后用name=value
指定的被称作关键字参数(Keyword Arguments)
Pandas
pandas 可以干什么:
- 从不同的数据源加载表格
- 查找指定的行列
- 计算统计数据
- 综合多种数据源
pandas 的表格类型:DataFrame
import pandas as pd # 加载 CSV df = pd.read_csv('ransom.csv') # 打印表单 print(df) # 打印表单前五行 print(df.head()) # 查看表格信息 print(df.info())

Matplotlib.pyplot
Import 与折线图初步
from matplotlib import pyplot as plt plt.plot(data1.x_values, data1.y_values) plt.plot(data2.x_values, data2.y_values) plt.show()
折线图进阶
# 添加横纵标签及标题 plt.xlabel("Letter") plt.ylabel("Frequency") plt.title("Ransom Note Letters") # 指定标题文字大小 plt.title("Plot title", fontsize=20) # 指定标签后添加图例 plt.plot(aditya.days, aditya.cases, label="Aditya") plt.plot(deshaun.days, deshaun.cases, label="Deshaun") plt.plot(mengfei.days, mengfei.cases, label="Mengfei") plt.legend() # 指定图例颜色(颜色来源 Web colors) plt.legend(color="green") # 指定折线颜色、粗细 plt.plot(x, y, color="tomato", linewidth=1) # 指定折线样式(- 为直线 -- 为虚线 -. 为虚线点线交错 : 为点线) plt.plot(x, y, linestyle='-.') # 指定折线标记(x为叉 s为方 o为圆 d为钻石菱形 *为五角星 h为六边形) plt.plot(x, y, marker='*') # 添加任意位置文本:横坐标、纵坐标、文字 plt.text(5, 9, "Unusually low H frequency!") # 指定表格风格 plt.style.use('fivethirtyeight') # 查看可用风格 print(plt.style.available) # 正常显示中文字体 plt.rcParams['font.sans-serif']=['Microsoft YaHei']
散点图
# scatter 散点图,参数为横坐标与纵坐标序列 plt.scatter(df.age, df.height) plt.xlabel('Age (in months)') plt.ylabel('Height (in inches)') plt.show() # 调整标记透明度(alpha 0 到 1) plt.scatter(df.age, df.height, marker='o', alpha=0.1)
柱形图
# 柱形图 plt.bar(df.precinct, df.pets_abducted) plt.ylabel('Pet Abductions') plt.show() # 条形图(横向柱形图,horizonal) plt.barh(df.precinct, df.pets_abducted) plt.ylabel('Pet Abductions') plt.show() # 增加柱形图误差线(yerr) plt.bar(df.precinct, df.pet_abductions, yerr=df.error) # 累积柱状图(bottom) plt.bar(df.precinct, df.dog, label='Dog') plt.bar(df.precinct, df.cat, bottom=df.dog, label='Cat')


直方图
# 默认 10 分类直方图 plt.hist(gravel.mass) # 更改分类桶数量(bins) plt.hist(gravel.mass, bins=40) # 更改上下限 (range=tuple) plt.hist(gravel.mass, range=(50, 100)) # 归一化,变数量为频率(density) plt.hist(male_weight, density=True) plt.hist(female_weight, density=True)

评论