python - 可视化时间序列热图中的缺失值

标签 python pandas dataframe heatmap missing-data

我在大数据分析方面确实是新手。 假设我有一个具有以下特征的大数据。我想可视化特定小时内每个 id 的燃料参数缺失值(无值)的百分比。我想绘制一个图表,x 轴是时间序列(时间列),y 轴是“id”,颜色将指示其缺失的燃料百分比。 我根据“id”和“小时”对数据库进行分组

我不知道如何以一种好的方式为所有 ID 可视化缺失值。例如,如果特定小时内特定id的缺失值燃料的百分比是100%,则该特定时间和该“id”的颜色可以是灰色的。如果燃料中缺失值的百分比为 50%,则颜色可为浅绿色。如果燃料中缺失值的百分比为 0%,则颜色可以为深绿色。 根据 ID 和时间分组后,颜色必须基于燃料中缺失值的百分比。

    id    time                   fuel
0   1     2022-02-26 19:08:33    100
2   1     2022-02-26 20:09:35    None
3   2     2022-02-26 21:09:35    70
4   3     2022-02-26 21:10:55    60
5   4     2022-02-26 21:10:55    None
6   5     2022-02-26 22:12:43    50
7   6     2022-02-26 23:10:50    None

例如,在下面的代码中,我计算了特定 id 每小时缺失值的百分比:

df.set_index('ts').groupby(['id', pd.Grouper(freq='H')])['fuell'].apply(lambda x: x.isnull().mean() * 100)

有什么解决办法吗?

最佳答案

更新:热图现在绘制 id时间 与 null fuel 的百分比。我在本文末尾保留了关于 id vs time vs fuel 的原始答案。


I want something almost like a github style calendar.

为了模仿 GitHub 贡献矩阵,请将分组的空百分比重置为数据框和 pivot每行 1 个 id,每列 1 小时。然后使用sns.heatmap根据空 fuel 的百分比为每个单元格着色。

# convert to proper dtypes
df['time'] = pd.to_datetime(df['time'])
df['fuel'] = pd.to_numeric(df['fuel'], errors='coerce')

# compute null percentage per (id, hour)
nulls = (df.set_index('time')
           .groupby(['id', pd.Grouper(freq='H')])['fuel']
           .apply(lambda x: x.isnull().mean() * 100))

# pivot into id vs time matrix
matrix = (nulls.reset_index(name='null (%)')
               .pivot(index='id', columns='time', values='null (%)'))

# plot time series heatmap
sns.heatmap(matrix, square=True, vmin=0, vmax=100, cmap='magma_r', cbar_kws={'label': 'null (%)'},
            linewidth=1, linecolor='lightgray', clip_on=False,
            xticklabels=matrix.columns.strftime('%b %d, %Y\n%H:%M:%S'))


原始:这是为了按时间燃料可视化id:

  1. 转入 idtime 矩阵。通常pivot没问题,但是由于您的真实数据包含重复索引,因此请使用 pivot_table .
  2. resample时间列转换为每小时的平均值。
  3. 使用 sns.heatmap 绘制时间序列矩阵.
# convert to proper dtypes
df['time'] = pd.to_datetime(df['time'])
df['fuel'] = pd.to_numeric(df['fuel'], errors='coerce')

# pivot into id vs time matrix
matrix = df.pivot_table(index='id', columns='time', values='fuel', dropna=False)

# resample columns into hourly means
matrix = matrix.resample('H', axis=1).mean()

# plot time series heatmap
sns.heatmap(matrix, square=True, cmap='plasma_r', vmin=0, vmax=100, cbar_kws={'label': 'fuel (%)'},
            linewidth=1, linecolor='lightgray', clip_on=False,
            xticklabels=matrix.columns.strftime('%b %d, %Y\n%H:%M:%S'))

关于python - 可视化时间序列热图中的缺失值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71610279/

相关文章:

python - 为什么在与列表相乘时将 float64 转换为 int?

python - 在 Python 中重新格式化制表符分隔的数据

R数据表: How to sum variables by group based on a condition?

python - py2exe到exe文件,它可以在我的电脑上运行但在其他电脑上显示DLL加载失败

python - pickle:它如何 pickle 一个函数?

Python,Pandas——如何根据多列高于特定值的条件搜索行?

python - 在 pandas 中使用 openpyxl 编写时损坏的工作簿

python - 生成指定范围内的N个唯一随机整数

python - 使用常量初始化数据帧

python - 数据框透视而不对列名称进行排序?