关键词

python机器学习使数据更鲜活的可视化工具Pandas_Alive

介绍

Pandas_Alive 是一个可以将 Pandas 数据帧 (dataframe) 即数据可视化为动画的工具。它为数据科学家提供了一个可视化的工具来探索和呈现数据。Pandas_Alive 使用 Matplotlib 音乐人才晋升来创建动画,并提供了更具可读性和易于使用的 Python 代码。

安装

Pandas_Alive 不是 Python 标准库的一部分。因此,需要先安装它:

!pip install pandas_alive

使用Pandas_Alive

导入 Pandas_Alive 和 Pandas,然后使用 Pandas 中的 read_csv() 函数从 CSV 文件中读取数据。加载完成数据后,使用 Pandas_Alive 中的 animate_dataframe() 函数将数据转换为动态图形。

import pandas as pd
from pandas_alive import animate_dataframe

# 读取数据
df = pd.read_csv('data.csv')

# 将数据可视化为动态图形
animate_dataframe(df, 'output.gif')

应该现在已经可以看到一个漂亮的动态 GIF 图像输出了。

示例1: 疫情变化趋势

下面我将使用 Pandas_Alive 实现一个简单的动态图形展示新冠肺炎的情况变化。我们将使用 Johns Hopkins 大学的新冠肺炎数据集来实现这个功能。

import pandas as pd
from datetime import datetime, timedelta
from pandas_alive import animate_dataframe
import matplotlib.pyplot as plt

# 读取数据
df = pd.read_csv('https://raw.githubusercontent.com/datasets/covid-19/master/data/time-series-19-covid-combined.csv')
df = df[df['Country/Region'] == 'China']
df = df.groupby(['Date'])[['Confirmed', 'Deaths', 'Recovered']].sum()

# 累积增长率
df['Confirmed_New'] = df['Confirmed'].diff().fillna(0)
df['Deaths_New'] = df['Deaths'].diff().fillna(0)
df['Recovered_New'] = df['Recovered'].diff().fillna(0)

# 时间格式转换
df.index = pd.to_datetime(df.index)

# 将数据可视化为动态图形
fig, ax = plt.subplots(figsize=(12, 6))
animate_dataframe(df, filename='china_covid.gif', ax=ax, period_fmt='%m-%d', title='China Covid-19 Trends')

在这个示例中,我们首先从 Github 中读取 Johns Hopkins 数据集。然后我们将数据限制为仅包含中国,且聚合为每天。我们还计算了每日累计增长率,并将我们的日期格式转换为 Pandas 可以理解的格式。最后,我们将数据帧传入在 matplotlib 图表上进行可视化。我们还指定了图表的外观,包括标题和图例。

示例2: 股票价格趋势

下面是一个使用 Pandas_Alive 来可视化股票价格趋势的简单示例代码:

import pandas as pd
import yfinance as yf
from pandas_alive import animate_dataframe

# 读取股票数据
df = yf.download('AAPL', start='2015-01-01', end='2021-06-01', progress=False)

# 将数据可视化为动态图形
animate_dataframe(df, period_fmt='%Y-%m', title='AAPL Stock Price', filename='aapl_stock.gif')

在这个示例中,我们使用 yfinance 库从 Yahoo! Finance 获得 AAPL 股票数据。然后,我们将数据帧传入 animate_dataframe() 函数来创建指定的图形。为了更好地查看趋势数据,我们指定了期间格式 “%Y-%m”,以表示股票价格变化的每一个月。最后,我们将结果保存为动画 GIF 文件。

本文链接:http://task.lmcjl.com/news/17496.html

展开阅读全文