【问题标题】:ValueError: Length mismatch: Expected axis has 23 elements, new values have 2 elements. Pandas length mismatchValueError:长度不匹配:预期轴有 23 个元素,新值有 2 个元素。熊猫长度不匹配
【发布时间】:2020-01-23 03:34:37
【问题描述】:

当我运行我的代码时,我正在尝试使用从 csv 加载的数据计算 Pearson 系数相关性 - 我收到不匹配错误,不知道如何摆脱它。

这是 Python 3。我尝试将值存储在一个新变量中

def correl(filename, header_one, header_two):

    df =pd.read_csv(filename)

    df.columns = [header_one, header_two]

    x= np.asarray(df[header_one])
    y= np.asarray(df[header_two])

    n_times_sum_of_x_times_y = len(x) * np.sum(np.multiply(x,y))

    sum_of_x = np.sum(x)
    sum_of_y = np.sum(y)


    n_times_sum_of_x_squared = len(x) * np.sum(np.multiply(x, x))
    n_times_sum_of_y_squared = len(x) * np.sum(np.multiply(y, y))

    sum_of_x_squared = sum_of_x ** 2
    sum_of_y_squared = sum_of_y ** 2

    numerator = n_times_sum_of_x_times_y - sum_of_x * sum_of_y
    denominator_squared = (n_times_sum_of_x_squared - sum_of_x_squared) * (n_times_sum_of_y_squared - sum_of_y_squared)
    denominator = np.sqrt(denominator_squared)

    p_correl_coefficient = (numerator / denominator)

    return(p_correl_coefficient)

#print(correl("imdb.csv", 'gross', 'budget'))

我在运行代码时遇到的实际错误:

文件“C:\Users\ruthi\Anaconda3\lib\site-packages\pandas\core\generic.py”,第 638 行,在 _set_axis self._data.set_axis(轴,标签)

文件“C:\Users\ruthi\Anaconda3\lib\site-packages\pandas\core\internals\managers.py”,第 155 行,在 set_axis '值有 {new} 个元素'.format(old=old_len, new=new_len)) ValueError:长度不匹配:预期轴有 23 个元素,新值有 2 个元素

【问题讨论】:

  • 错误在哪一行?
  • 错误在这一行:df.columns = [header_one, header_two]

标签: python python-3.x function


【解决方案1】:

这意味着在文件中您有 23 列,但您尝试仅用 2 列重命名它们。如果header_oneheader_two 是现有列的名称,请执行df = df[[header_one, header_two]],如果不是,请先选择您感兴趣的两列,然后将它们重命名为df.columns = [header_one, header_two]

【讨论】:

  • 当我尝试第一个时 - 我得到了 nan,但在第二次重命名时,我得到了那个错误......我的 csv 有 23 列但在我的代码中我只传递了我不想要的两列确定为什么要检查其他函数-这就是我调用函数的方式: print(correl("imdb.csv", 'gross', 'budget'))
  • @RuthIneh 如果header_oneheader_two 是列的名称,你不需要重命名任何东西,甚至不需要做df = df[[header_one, header_two]]。如果您得到nan 作为计算结果,那是一个不同的问题,这与您的数据有关,因为您可能在其中缺少值。
猜你喜欢
  • 2020-12-18
  • 1970-01-01
  • 2020-07-10
  • 2017-12-06
  • 1970-01-01
  • 1970-01-01
  • 2018-09-21
  • 2020-09-09
  • 1970-01-01
相关资源
最近更新 更多