1

Let's say I have a dataframe like this:

  columnA  columnB
0   10        90
1   83        17
2   30        21
...

and I have a function like this:

def my_func(a, b):
    value = #do some calculation
    return value

Now I want to get a new column columnC for my dataframe based on the calculations of the function.
Obviously, df["columnC"]= my_func(df["columnA"], df["columnB"]) does not work.

What can I do to add the column?

Sven
  • 1,014
  • 1
  • 11
  • 27

2 Answers2

2

The right way to do it is:

df['c'] = df.apply(lambda row: my_func(row['a'], row['b']), axis=1)
yonatansc97
  • 584
  • 6
  • 16
0

I found a workaround. It's a bit hacky though...

df["columnC"]=pd.Series([my_func(row["columnA"], row["columnB"])for index, row in df.iterrows()], index=df.index)
Sven
  • 1,014
  • 1
  • 11
  • 27