1

I have a data frame in python, and I want to do a simple calculation on row level. How can can I do it in Python?

Current Table

product ct cost1 cost2 cost3
1000 10 100 20
2000 200 100 30

Calculation Concept

product ct cost1 cost2 cost3
1000 10/1000 100/1000 20/1000
2000 200/2000 100/2000 30/2000

Wanted Output

product ct cost1 cost2 cost3
1000 0.01 0.1 0.02
2000 0.1 0.05 0.015
2
  • 1
    Isn't 20/1000=0.020? Commented Jul 28, 2021 at 15:18
  • 1
    In general, pandas functions that apply across a column or row will have an axis parameter Commented Jul 28, 2021 at 15:21

2 Answers 2

2

You can use pandas.DataFrame.filter to get the required columns (If you have the static columns, you can manually assign them to a list), and then use div to divide, and finally assign back all the values to the selected columns:

>>> cols = df[:0].filter(like='cost').columns.to_list()
>>> df[cols] = df[cols].div(df['product ct'], axis=0)

OUTPUT:

   product ct  cost1  cost2  cost3
0        1000   0.01   0.10  0.020
1        2000   0.10   0.05  0.015
Sign up to request clarification or add additional context in comments.

Comments

2

Try using divide along the required axis:

df[["cost1", "cost2", "cost3"]] = df[["cost1", "cost2", "cost3"]].divide(df["product ct"], axis=0)
>>> df
   product ct  cost1  cost2  cost3
0        1000   0.01   0.10  0.020
1        2000   0.10   0.05  0.015

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.