2

I have a pandas df and I would like to add values for each row from the "total_load" column with the "Battery capacity" column. For example 4755 +(-380) = 4375 and so on. Obviously, what I am doing right now is for every row in the "Battery capacity" column do: 5200 - the value from "total_load" column. Any ideas how I can write that? Should I use an for loop?

 df["Battery capacity"] = 5200 + df["total_load"] 

enter image description here

Output should be something like:

time                total_load   battery capacity
2016-06-01 00:00:00   -445        4755
2016-06-01 01:00:00   -380        4375
2016-06-01 02:00:00   -350        4025

Thanks!

2
  • 1
    What's wrong with how you are doing it now? df["Battery capacity"] = 5200 + df["total_load"] The data in your example appears to be shifted by one row (i.e. 4775 is on the first row and -380 is on the second), so perhaps you want to perform an operation on the shifted data? Commented Aug 15, 2017 at 17:16
  • Hey Alex, right now I always substract the values from the total_load column with the value "5200". I wanted, as you mentioned, perform the operation on the shifted data. It worked out with .cumsum() as Scott Boston wrote in his answer below! Commented Aug 16, 2017 at 12:36

1 Answer 1

2

IIUC, use cumsum to get a "running total" of total_load:

df['Battery capacity'] = df['total_load'].cumsum() + 5200

Output:

                     Battery capacity  total_load
time                                             
2016-01-01 00:00:00            4755.0      -445.0
2016-01-01 01:00:00            4375.0      -380.0
2016-01-01 02:00:00            4025.0      -350.0
2016-01-01 03:00:00            3685.0      -340.0
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Scott! Works perfectly. But I have one more question: What if I want to break cumsum once battery capacity is at a certain value? For example if Battery capacity reached 0, I don't want pandas to substract anymore. How could I implement that into this df? For example: df['Battery capacity'] = df['total_load'].cumsum(if battery capacity = 0 then stop substracting) + 5200.
@harald12345 Look at np.where it as much like an if-then statement. If you start a new question, I am sure myself or someone will answer it quickly.
ok, I will have a luck at np but might also start a new question! cheers

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.