Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help with a code.
#6
Can try like this.
I think there most be a better way than duplicate which make i kind of messy.
import pandas as pd
pd.set_option('display.expand_frame_repr', False)
import re

def expand_duplicates(df):
    expanded_rows = []
    pattern = re.compile(r'^(.*?)(\d+)(.*?)$')
    for key_value in df.iloc[:, 0].unique():
        group = df[df.iloc[:, 0] == key_value]
        expanded_row = {df.columns[0]: key_value}
        group_counter = 1
        for _, row in group.iterrows():
            for col in df.columns[1:]:
                match = pattern.match(col)
                if match:
                    col_prefix, _, col_suffix = match.groups()
                    col_key = f"{col_prefix}{group_counter}{col_suffix}"
                    expanded_row[col_key] = row[col]
            group_counter += 1
        expanded_rows.append(expanded_row)
    return pd.DataFrame(expanded_rows)

input_path = 'input.csv'
output_path = 'output.csv'
input_df = pd.read_csv(input_path, sep='\t')
expanded_df = expand_duplicates(input_df)
#print(expanded_df)
expanded_df.to_csv(output_path, index=False, sep='\t')
Reply


Messages In This Thread
Need help with a code. - by HanzoSW - Nov-29-2023, 06:35 PM
RE: Need help with a code. - by snippsat - Nov-29-2023, 07:54 PM
RE: Need help with a code. - by HanzoSW - Nov-29-2023, 08:33 PM
RE: Need help with a code. - by snippsat - Nov-29-2023, 09:37 PM
RE: Need help with a code. - by HanzoSW - Nov-30-2023, 09:45 AM
RE: Need help with a code. - by snippsat - Nov-30-2023, 04:33 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020