如何绘制函数的结果?

How to plot results from functions?

拥有系列数据并尝试计算某些值,但在尝试绘制它们时它不起作用。

# import pandas as pd
import pandas as pd
  
# import numpy as np
import numpy as np
  
# simple array
data = np.array([0,0,1,1,1])
  
ser = pd.Series(data)
print('The mean is ' + str(ser.mean()))

# find the variance
print('The variance is ' + str(ser.var()))

ser.mean().plot.bar(rot=0) # Attempt to use barplot
ser.var().plot.bar(rot=0) # Attempt to use barplot

以上给出如下错误:

The mean is 0.6
The variance is 0.30000000000000004
AttributeError: 'float' object has no attribute 'plot'

在一个图中同时显示这两个值会很酷。

您尝试使用的函数仅适用于 pandas DataFrame/Series,但您不能使用它来绘制 'float'、'int' 值。

对于这种情况,要么将均值和方差值存储到 dataframe/series,如下所示

d = [ser.mean(),ser.var()]
df = pd.Series(d) #pd.DataFrame(d) also works
ax = df.plot.bar(rot=1)
ax.set_xticklabels(['Mean','Variance'])

或者您可以使用其他包来绘制条形图。