Pandas Dataframe ValueError: Shape of passed values is (X, ), indices imply (X, Y)

后端 未结 2 1346
既然无缘
既然无缘 2020-12-10 02:33

I am getting an error and I\'m not sure how to fix it.

The following seems to work:

def random(row):
   return [1,2,3,4]

df = pandas.DataFrame(np.r         


        
相关标签:
2条回答
  • 2020-12-10 02:54

    I use the code below it is just fine

    import numpy as np    
    df = pd.DataFrame(np.array(your_data), columns=columns)
    
    0 讨论(0)
  • 2020-12-10 02:56

    If your goal is add new column to DataFrame, just write your function as function returning scalar value (not list), something like this:

    >>> def random(row):
    ...     return row.mean()
    

    and then use apply:

    >>> df['new'] = df.apply(func = random, axis = 1)
    >>> df
              A         B         C         D       new
    0  0.201143 -2.345828 -2.186106 -0.784721 -1.278878
    1 -0.198460  0.544879  0.554407 -0.161357  0.184867
    2  0.269807  1.132344  0.120303 -0.116843  0.351403
    3 -1.131396  1.278477  1.567599  0.483912  0.549648
    4  0.288147  0.382764 -0.840972  0.838950  0.167222
    

    I don't know if it possible for your new column to contain lists, but it deinitely possible to contain tuples ((...) instead of [...]):

    >>> def random(row):
    ...    return (1,2,3,4,5)
    ...
    >>> df['new'] = df.apply(func = random, axis = 1)
    >>> df
              A         B         C         D              new
    0  0.201143 -2.345828 -2.186106 -0.784721  (1, 2, 3, 4, 5)
    1 -0.198460  0.544879  0.554407 -0.161357  (1, 2, 3, 4, 5)
    2  0.269807  1.132344  0.120303 -0.116843  (1, 2, 3, 4, 5)
    3 -1.131396  1.278477  1.567599  0.483912  (1, 2, 3, 4, 5)
    4  0.288147  0.382764 -0.840972  0.838950  (1, 2, 3, 4, 5)
    
    0 讨论(0)
提交回复
热议问题