JavaNewb
JavaNewb

Reputation: 155

How to perform element wise operation on two sets of columns in pandas

I have the dataframe:

 c1 | c2 | c3 | c4
 5  |  4 | 9  | 3

How could I perform element wise division (or some other operation) between c1/c2 and c3/c4

So that the outcome is:

.5555 | 1.33333

I've tried:

df[['c1', 'c2']].div(df[['c3', 'c4']], axis='index'))

But that just resulted in NaNs.

Upvotes: 2

Views: 6983

Answers (3)

rafaelc
rafaelc

Reputation: 59274

Pretty straightforward, just divide by the values

df[['c1', 'c2']]/df[['c3','c4']].values

Orders matter, so make sure to use correct ordering in the denominator. No need to recreate the DataFrame

Upvotes: 3

Nick Brady
Nick Brady

Reputation: 6582

I'm not positive I'm understanding your question correctly , but you can literally just divide the series.

df['c1/c2'] = df['c1'] / df['c2']

See this answer: How to divide two column in a dataframe

EDIT: Okay, I understand what OPs asking now.. Please see other answer.

Upvotes: 1

jpp
jpp

Reputation: 164693

One solution is to drop down to NumPy and create a new dataframe:

res = pd.DataFrame(df[['c1', 'c2']].values / df[['c3', 'c4']].values)

print(res)

          0         1
0  0.555556  1.333333

Upvotes: 2

Related Questions