Pandas Dataframe ValueError:传递值的形状是(X,),索引暗示(X,Y)

use*_*204 17 ipython dataframe python-2.7 pandas

我收到错误,我不知道如何解决它.

以下似乎有效:

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

df = pandas.DataFrame(np.random.randn(5, 4), columns=list('ABCD'))

df.apply(func = random, axis = 1)
Run Code Online (Sandbox Code Playgroud)

我的输出是:

[1,2,3,4]
[1,2,3,4]
[1,2,3,4]
[1,2,3,4]
Run Code Online (Sandbox Code Playgroud)

但是,当我将其中一列更改为1或None之类的值时:

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

df = pandas.DataFrame(np.random.randn(5, 4), columns=list('ABCD'))
df['E'] = 1

df.apply(func = random, axis = 1)
Run Code Online (Sandbox Code Playgroud)

我得到了错误:

ValueError: Shape of passed values is (5,), indices imply (5, 5)
Run Code Online (Sandbox Code Playgroud)

我已经在这几天摔跤了,似乎什么都没有用.有趣的是,当我改变时

def random(row):
   return [1,2,3,4]
Run Code Online (Sandbox Code Playgroud)

def random(row):
   print [1,2,3,4]
Run Code Online (Sandbox Code Playgroud)

一切似乎都正常.

这个问题是一个更清楚的方式来提出这个问题,我觉得这个问题可能令人困惑.

我的目标是为每一行计算一个列表,然后创建一个列.

编辑:我最初从一个拥有一列的数据框开始.我在4个不同的应用步骤中添加4列,然后当我尝试添加另一列时,我收到此错误.

Rom*_*kar 9

如果您的目标是向DataFrame添加新列,只需将函数编写为返回标量值(不是列表)的函数,如下所示:

>>> def random(row):
...     return row.mean()
Run Code Online (Sandbox Code Playgroud)

然后使用申请:

>>> 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
Run Code Online (Sandbox Code Playgroud)

我不知道你的新列是否可能包含列表,但它绝对可能包含元组((...)而不是[...]):

>>> 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)
Run Code Online (Sandbox Code Playgroud)