【问题标题】:shape of passed values differing from indices using init function传递值的形状与使用 init 函数的索引不同
【发布时间】:2021-10-23 18:41:30
【问题描述】:

df1:

A B C D
a 1 2 3 4
b 23 45 423 23
c 12 21 21 3
s 1221 12 21 12
s 21 34 5 6
other = pd.DataFrame({'A': [0,25], 'B': [0,25], 'C': [0,25], 'D': [0,20]},
index =['a','b','c','s','s'])

ValueError: Shape of passed values is (2, 4), indices imply (5, 4)

【问题讨论】:

  • 将字典传递给 pd.DataFrame() 时,由于字典的键被解释为列名,因此您的 DataFrame 将有 2 行和 4 列。将包含 5 个元素的数组传递给索引关键字参数将引发错误,因为它期望 DataFrame 有 5 行。您可以将其更改为 index=["a", "b"] 或使键 A-D 下的每个列表具有 5 个元素。

标签: python pandas numpy jupyter-notebook jupyter


【解决方案1】:

您的索引多于行。而是这样做:

other = pd.DataFrame({'A': [0,25], 'B': [0,25], 'C': [0,25], 'D': [0,20]}, index =['index1','index2'])

因为在这个新数据框中,您只有 2 行(0 和 25)

【讨论】:

    【解决方案2】:

    @Anabel 正确地指出了问题。

    一种调试方法是首先创建数据框而不指定索引:

    other = pd.DataFrame(
        {'A': [0,25], 'B': [0,25], 'C': [0,25], 'D': [0,20]}
    )
    print(other)
    

    输出将是:

        A   B   C   D
    0   0   0   0   0
    1  25  25  25  20
    

    从这里您会观察到创建的 df 只有两个索引,即 0 和 1。因此,要创建自定义索引,您必须使用:

    other = pd.DataFrame(
        {'A': [0,25], 'B': [0,25], 'C': [0,25], 'D': [0,20]},
        index=['a', 'b']
    )
    print(other)
    

    您的输出将是:

        A   B   C   D
    a   0   0   0   0
    b  25  25  25  20
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-24
      • 2019-05-14
      • 2015-02-27
      • 2019-08-25
      • 1970-01-01
      • 1970-01-01
      • 2020-01-12
      相关资源
      最近更新 更多