0

enter image description here

I have three separate columns: Link_Id, NEW, Length in a data frame.

I want to group similar Link_Ids together and then collect their Length values, out of those having the maximum Length value I want to return their (Link_Id) and (NEW) column values.

import pandas as pd
# List all columns you want to include in the dataframe. I include all with:
cols = ['LINK_ID', 'NEW', 'Length']  # Or list them manually: ['kommunnamn', 'kkod', ... ]
# A generator to yield one row at a time
datagen = ([f[col] for col in cols] for f in vlayer.getFeatures())
df = pd.DataFrame.from_records(data=datagen, columns=cols)

dff = df.groupby((df['LINK_ID'].shift() != df['LINK_ID']).cumsum())

for k, v in dff:
    print(f'[group {k}]')
    print(v)

result = df.groupby('LINK_ID').agg({'Length': ['max']})
1
  • Please don't post images of your data. You can provide a sample of your dataframe as a table or by posting the output of df.head().to_dict() Mar 11, 2022 at 18:14

1 Answer 1

0

IIUC, try:

result = df.loc[df.groupby("LINK_ID")["Length"].idxmax()]
1
  • any ideas on how to apply a for loop and get print of the values to know whether this worked or not? @not_speshal and how do I retrive other column values. Mar 12, 2022 at 5:14

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.