Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Subtracting data in a row based on similar values in a different column

I have sample of a much larger dataframe here:

import pandas as pd

data = {'Name': [27, 27, 30, 30, 43, 43, 50, 62, 62],
        'Time': [10, 30, 23.4, 28.6, 10, 15, 20, 25, 50]}

df = pd.DataFrame(data)

I want to be able to create a new column or a new dataframe that is able to subtract the Time values for each of the same numbers in the Name column.

Expected Outcome:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Name      Time Bucket
27            20
30            5.2
43            5
50            20
62            25

I am not too sure how I need to go about this.

>Solution :

Try:

out = df.assign(Time=df.groupby('Name')['Time'].diff().fillna(df['Time'])) \
        .drop_duplicates('Name', keep='last')
print(out)

# Output
   Name  Time
1    27  20.0
3    30   5.2
5    43   5.0
6    50  20.0
8    62  25.0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading