如何在遍历 pandas 数据框时创建新列并插入行值

How to create new column and insert row values while iterating through pandas data frame

我正在尝试创建一个逐行遍历 pandas 数据框的函数。我想根据其他列的行值创建一个新列。我的原始数据框可能如下所示:

df:

   A   B
0  1   2
1  3   4
2  2   2

现在我想创建一个新列,在每个索引位置填充列 A - 列 B 的行值,以便结果如下所示:

 df:

       A   B   A-B
    0  1   2   -1
    1  3   4   -1
    2  2   2    0

我的解决方案有效,但只有当我不在函数中使用它时才有效:

for index, row in df.iterrows():
        print index
        df['A-B']=df['A']-df['B']

这给了我想要的输出,但是当我尝试将它用作函数时,出现错误。

def test(x):
    for index, row in df.iterrows():
        print index
        df['A-B']=df['A']-df['B']
    return df
df.apply(test)

ValueError: cannot copy sequence with size 4 to array axis with dimension 3

我在这里做错了什么,我怎样才能让它工作?

这是因为 apply 方法默认适用于列,如果您想要遍历行,请将 axis 更改为 1:

axis : {0 or ‘index’, 1 or ‘columns’}, default 0

  • 0 or ‘index’: apply function to each column
  • 1 or ‘columns’: apply function to each row
df.apply(test, axis=1)

编辑

我认为您需要对每一行进行一些复杂的操作。如果您只需要相互减去列:

df['A-B'] = df.A - df.B

正如 Anton 所指出的,您应该使用 axis=1 参数执行 apply 函数。然而,没有必要像在函数测试中那样循环遍历行,因为 apply documentation 提到:

Objects passed to functions are Series objects

因此您可以将函数简化为:

def test(x):
    x['A-B']=x['A']-x['B']
    return x

然后 运行:

df.apply(test,axis=1)

请注意,实际上您将测试的参数命名为 x,而根本没有在函数 test 中使用 x

最后我要评论说你可以用 pandas 进行列操作(即没有 for 循环),只需这样做:

df['A-B']=df['A']-df['B']

另见:

  • how to compute a new column based on the values of other columns in pandas - python
  • How to apply a function to two columns of Pandas dataframe