【问题标题】:How to make a histogram for each row of a Pandas dataframe?如何为 Pandas 数据框的每一行制作直方图?
【发布时间】:2020-05-11 12:01:42
【问题描述】:

我是否使用 for 循环?我需要使用 iterrows() 吗?

x = df.T[0]
y = df2.T[0]
plt.hist(x, bins=[-3.0, -2.0, -1.0, 0, 1.0, 2.0, 3.0], alpha=0.5, label='x')
plt.hist(y, bins=[-3.0, -2.0, -1.0, 0, 1.0, 2.0, 3.0], alpha=0.5, label='y')
plt.legend(loc='upper right')
plt.show()

我如何制作 df.T[i+1]?

源数据示例(注意我没有截取列名,因为它们包含敏感信息): data

我正在尝试对每一行执行此操作(这是使用第一行的数据完成的): visualisation

【问题讨论】:

  • 请添加您的源数据样本。
  • 你想为每一行单独绘制一个图吗?

标签: python pandas for-loop matplotlib


【解决方案1】:

由于您有 pandas 数据框,因此您可以使用 pandas 图形工具。检查这个例子:

# import modules
import pandas as pd
import matplotlib.pyplot as plt

# Data frame creation
df = pd.DataFrame([[0, 1], [1, 1], [-1, 0], [0, -2], [2, 0], [-3, -2], [2, 0], [2, 1], [3, 0], [0, -1], [1, 1], [0, 0],
                   [1, 2], [0, 0], [1, -1], [0, -3], [-1, -2], [1, 0], [0, -2]], columns=['column_1', 'column_2'])
num_bins = 5  # Change this number as you need

# Create separate histograms
ax = df.hist(bins=num_bins)

# Create overlapped histograms
ax = df['column_1'].hist(bins=num_bins, label='column_1')
ax = df['column_2'].hist(bins=num_bins, label='column_2')
plt.legend(loc='upper right')
title_obj = plt.title('Overlapped Histogram', color='dimgrey')

查看此链接了解详细信息:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.hist.html

【讨论】:

    【解决方案2】:

    在我看来,唯一可接受的解决方案是创建直方图 对于每一行单独。首先在单独的变量中定义bins

    bins=[-3.0, -2.0, -1.0, 0, 1.0, 2.0, 3.0]
    

    然后,例如对于第 0 行,您可以运行:

    df.iloc[0].hist(bins=bins);
    

    注意尾随 ; 以避免额外的打印输出(至少在 Jupyter 中)。

    尝试在一张图片中叠加超过 2 行的数据 会使这张图片完全不可读。 请注意,您的 DataFrame 中有多达 107 行。

    另一种选择:将许多这样的图片并排放置 (水平),例如对于 5 个初始行,您可以运行:

    df.iloc[0:5].T.hist(bins=bins, sharey=True, layout=(1, 5), figsize=(12, 3));
    

    结果(对于您的样本数据)是:

    然后对每组连续的 5 行重复上述代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-06
      • 1970-01-01
      • 2020-05-19
      • 2021-12-26
      • 2021-05-26
      • 2021-11-22
      • 2018-11-03
      相关资源
      最近更新 更多