简体   繁体   English

如何使用 Pandas 将箱线图的结果导出到 csv 文件?

[英]How to export the result of a boxplot to a csv file with pandas?

I need to export the result of a boxplot output to a CSV file, but I'm not finding a way to do it.我需要将箱线图输出的结果导出到 CSV 文件,但我没有找到方法来做到这一点。

boxplot = df.boxplot(by='Time', 
                 column='Duration',
                 grid=False,
                 figsize=(16,10))

boxplot.to_csv('BoxplotResult.csv')

In the above example, I get the error: AttributeError: 'AxesSubplot' object has no attribute 'to_csv'.在上面的示例中,我收到错误消息:AttributeError: 'AxesSubplot' object has no attribute 'to_csv'。
Which I understand that the result of the boxplot operation is a AxesSubplot and AxesSubplot does not have to_csv method in it.我知道 boxplot 操作的结果是 AxesSubplot 并且 AxesSubplot 中没有 to_csv 方法。

Is there any way to export the results of a boxplot to a CSV file?有没有办法将箱线图的结果导出到 CSV 文件?

Given you are interested only in the numerical values, a shortcut would describe鉴于您只对数值感兴趣,快捷方式将describe

import pandas as pd
import numpy as np

df = pd.DataFrame({"A": np.random.randint(5, size=(10)), "B": np.random.randint(8, size=(10))})

df.describe()

Yielding,屈服,

            A          B
count   10.000000   10.000000
mean    2.100000    2.000000
std     1.449138    1.763834
min     0.000000    0.000000
25%     1.250000    1.000000
50%     2.000000    1.500000
75%     3.000000    3.500000
max     4.000000    5.000000

This contains all the information needed ( https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.describe.html ) and can simply be written to a CSV file as you already pointed out by:这包含所需的所有信息( https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.describe.html )并且可以简单地写入 CSV 文件,正如您已经指出的那样:

df.describe().to_csv("my_csv.csv")

EDIT编辑

Saving the actual plot can not be done using a CSV file.使用 CSV 文件无法保存实际绘图。 To do so, use you can simply create a pyplot figure object and plot on its axes like:为此,您可以简单地创建一个 pyplot 图形对象并在其轴上绘图,例如:

from matplotlib import pyplot as plt

fig, ax = plt.subplots()
df.boxplot(grid=False, figsize=(16,10), ax=ax)

fig.savefig("my_figure.png", dpi=72)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM