I am trying to create a function that iterates through a pandas dataframe row by row. I want to create a new column based on row values of other columns. My original dataframe could look like this:
df:
A B
0 1 2
1 3 4
2 2 2
Now I want to create a new column filled with the row values of Column A - Column B at each index position, so that the result looks like this:
df:
A B A-B
0 1 2 -1
1 3 4 -1
2 2 2 0
the solution I have works, but only when I do NOT use it in a function:
for index, row in df.iterrows():
print index
df['A-B']=df['A']-df['B']
This gives me the desired output, but when I try to use it as a function, I get an error.
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
What am I doing wrong here and how can I get it to work?