python - Pandas:计算线性模型系数的脚本在 Linux 上运行良好,但在 Windows 10 上运行不佳

标签 python pandas

以下脚本在 Linux (Mint 18.1) 上运行良好。

该函数创建一个每月销售额的数组“Y”,并从数组中删除 nan 值。然后它创建一个 numpy.arange 数组“X”,其长度从 1 到 Y 的长度。 然后,它根据 X 和 Y 建立线性模型,并计算系数。

import pandas as pd
import numpy as np
from io import StringIO
from sklearn import linear_model as lm

data=
'''Fruit  jan  feb  mar  apr  may  jun  jul  aug  sep  oct  nov  dec
Apples    nan  nan  nan  600  550  620  nan  nan  300  100  200  50
Bananas   740  720  780  700  250  140  20   nan  nan  nan  nan  nan
Kiwis     nan  nan  nan  nan  400  550  nan  500  nan  40   50   nan
Oranges   nan  300  350  300  400  500  nan  nan  nan  nan  nan  nan
Grapes    150  200  250  200  50   50   40   35   30   20   10   nan'''

def coefficient(row):
    y   =   np.array(row['jan':'dec'].astype(float))
    y   =   np.nan_to_num(y)
    y   =   y[y != 0]
    x   =   np.arange(1,len(y)+1).reshape(len(y),1)
    return lm.LinearRegression().fit(x,y).coef_

df          =   pd.read_csv(StringIO(data),delimiter='\s+')
df['COEF']  =   df.apply(coefficient,axis=1)

这个完全相同的脚本会在 Windows 10 上导致以下错误。

  File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\internals.py", line 109, in __init__
len(self.mgr_locs)))

ValueError: Wrong number of items passed 13, placement implies 1

在这两种情况下我都使用完全升级的 Anaconda 3。有谁知道为什么会发生这种情况,以及如何更改脚本以避免 Windows 上的错误?

最佳答案

根据我所做的一些测试,.coef_ 返回一个 numpy 数组,这会导致一些问题。更改以下行有效,我只是不确定结果是否是您想要的。

return lm.LinearRegression().fit(x,y).coef_[0]

关于python - Pandas:计算线性模型系数的脚本在 Linux 上运行良好,但在 Windows 10 上运行不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42530685/

相关文章:

python - Pandas 数据框 : is there any way to transform columns as row values in pandas

python - 具有多行和 HTML 标签的正则表达式

python - 类中的所有函数是否有 __enter__ 和 __exit__ 等价物?

python - Tensorflow:无法在 word2vec_basic.py 中可视化嵌入?

python - 从 Pandas 到excel的颜色格式

python - 如何在 seaborn 中使用 'hue' 参数绘制联合图

python - 在多列时间戳上使用 boolean 运算符的高效/优雅的方法

python - 解析多列 pandas

python - 当通过变量分配给字典时,pandas 中的数据框会带来行号和属性值

python - Pandas HDFStore : Saving and Retrieving a Series with Hierarchical Period Index