【问题标题】:Printing table in Jupyter NotebookJupyter Notebook 中的打印表格
【发布时间】:2017-03-12 18:12:21
【问题描述】:

如何打印包含 3 列(索引、协方差矩阵、均方误差)的表格?

from sklearn import linear_model # Machine Learning tool
import numpy as np # Mathematics and Linear Algebra tool
import pandas as pd # data structure tool
import matplotlib.pyplot as plt # scientific plotting tool
import seaborn as sns # # scientific plotting tool
%matplotlib inline

from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error

diabetes = datasets.load_diabetes() # Load the diabetes dataset
n = 10 # 10 datasets for analysis
y_train = diabetes.target[:-20]
y_test = diabetes.target[-20:]
MSE = np.empty([n,1]) # mean square error
COV = [None] * n # covariance
regr = [None] * n
table= [None] * n
for i in range(n):
    x = diabetes.data[:, np.newaxis, i] # select feature from dataset
    x_train = x[:-20]
    x_test = x[-20:]
    regr[i] = linear_model.LinearRegression()
    regr[i].fit(x_train, y_train)
    y_predict = regr[i].predict(x_test)
    MSE[i] = mean_squared_error(y_predict, y_test)
    COV[i] = np.cov(x_train.T, np.reshape(y_train,[422,1]).T)
    table[i] = [i, MSE[i], COV[i]]
    print(table[i])

矩阵table 包含所有必需的内容。但是我该如何调整它以使其易于理解?不需要闪亮的 LaTeX,但可以使用。

【问题讨论】:

  • 您好。我建议你创建一个最小的工作示例,因为你的问题与你发布的数据或算法无关,让它工作是浪费时间(目前没有)。
  • 现在可以了。对不起。

标签: python pandas jupyter


【解决方案1】:

使用 pandas.DataFrame() 代替:

import pandas as pd

df = pd.DataFrame()
a=range(10)
b=range(10,20)
c=range(20,30)
df['a']=a
df['b']=b
df['c']=c

df
   a   b   c
0  0  10  20
1  1  11  21
2  2  12  22
3  3  13  23
4  4  14  24
5  5  15  25
6  6  16  26
7  7  17  27
8  8  18  28
9  9  19  29

或一次性:

df = pd.DataFrame({'a': a, 'b': b, 'c': c})

df
   a   b   c
0  0  10  20
1  1  11  21
2  2  12  22
3  3  13  23
4  4  14  24
5  5  15  25
6  6  16  26
7  7  17  27
8  8  18  28
9  9  19  29

【讨论】:

  • 如果左列是从 0 到 9 的索引,中间列有 2x2 矩阵作为元素,而右列又是整数,这如何工作?
  • 旁注:请不要在你的代码中使用>>>,它是无用的,你自己也很难复制和运行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-19
  • 1970-01-01
  • 1970-01-01
  • 2019-02-27
  • 1970-01-01
  • 1970-01-01
  • 2018-09-28
相关资源
最近更新 更多