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

Assign values to a grouped by dataframe

given this dataframe how can I find where if rows are grouped by first name and last name, the row with type as ‘CA’ get its Value column set to the row with type as ‘GCA’ value? so in this example the first row Alice, Johnson, CA, 25 will have its value changed from 25 to 40

data = {
    'First Name': ['Alice', 'Alice', 'Alice', 'Alice', 'Bob'],
    'Last Name': ['Johnson', 'Johnson', 'Johnson', 'Johnson', 'Jack'],
    'Type': ['CA', 'DA', 'FA', 'GCA', 'CA'],
    'Value': [25, 30, 35, 40, 50]
}

so in this example the first row Alice, Johnson, CA, 25 will have its value changed from 25 to 40

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

>Solution :

maybe like this

data = {
    'First Name': ['Alice', 'Alice', 'Alice', 'Alice', 'Bob'],
    'Last Name': ['Johnson', 'Johnson', 'Johnson', 'Johnson', 'Jack'],
    'Type': ['CA', 'DA', 'FA', 'GCA', 'CA'],
    'Value': [25, 30, 35, 40, 50]
}
df = pd.DataFrame(data)
updated_df = df.copy()

gca_values = updated_df[updated_df['Type'] == 'GCA'].set_index(['First Name', 'Last Name'])['Value']
updated_df.loc[df['Type'] == 'CA', 'Value'] = updated_df[updated_df['Type'] == 'CA'].apply(
    lambda row: gca_values.get((row['First Name'], row['Last Name']), row['Value']), axis=1)

updated_df
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