|
import pandas as pd |
|
|
|
|
|
def data_processing(df: pd.DataFrame) -> pd.DataFrame: |
|
""" |
|
For each id, creates a new row with the longest content and the highest score |
|
from the available rows with the same id. Adds a boolean column 'updated' |
|
indicating whether the row was updated. |
|
|
|
Parameters: |
|
- df (pd.DataFrame): The input DataFrame with columns 'id', 'content', and 'score'. |
|
|
|
Returns: |
|
- pd.DataFrame: A DataFrame with unique ids, where each id is associated |
|
with the longest content available and the highest score from |
|
potentially different rows, and a boolean column 'updated'. |
|
""" |
|
|
|
|
|
original_df = df.copy() |
|
|
|
|
|
df['content_length'] = df['content'].str.len() |
|
|
|
|
|
idx_longest_content = df.groupby('id')['content_length'].idxmax() |
|
df_longest_content = df.loc[idx_longest_content][['id', 'content']] |
|
|
|
|
|
idx_highest_score = df.groupby('id')['score'].idxmax() |
|
df_highest_score = df.loc[idx_highest_score][['id', 'score']] |
|
|
|
|
|
df_merged = pd.merge(df_longest_content, df_highest_score, on='id') |
|
|
|
|
|
df_merged = df_merged.merge(original_df, on='id', suffixes=('', '_original')) |
|
|
|
|
|
df_merged['updated'] = (df_merged['content'] != df_merged['content_original']) |
|
|
|
|
|
df_merged.drop(columns=['content_original', 'score_original'], inplace=True) |
|
|
|
|
|
df_merged.drop_duplicates(subset='id', inplace=True) |
|
|
|
return df_merged |
|
|
|
|
|
if __name__ == '__main__': |
|
|
|
data = { |
|
'id': [1, 1, 2, 2, 3], |
|
'content': ['short', 'much longer content', 'mid', 'size', 'constant'], |
|
'score': [10, 5, 7, 9, 6], |
|
'another_column': ['a', 'a', 'b', 'b', 'c'] |
|
} |
|
|
|
df = pd.DataFrame(data) |
|
|
|
print("Original DataFrame:") |
|
print(df) |
|
print("\nFiltered DataFrame:") |
|
print(data_processing(df)) |
|
|