I'm wondering if there's a nicer way to address the following problem
I have a dataframe with the following example structure:
| Split_key | label | sub_label |
|---|---|---|
| A_B_C | 7 | "" |
| A_B_C | 7 | "" |
| A_B_C | 8 | "" |
| A_B_C | 8 | "" |
| A_B_C | 10 | "" |
| A_B_C | 10 | "" |
| D_E_F | 2 | "" |
| D_E_F | 7 | "" |
| D_E_F | 15 | "" |
| G_H_I | 1 | "" |
| G_H_I | 2 | "" |
| G_H_I | 3 | "" |
I wish to populate sub_label with a value that corresponds to splitting the value in Split_key on the "_" character and grabs the correct element based on label. The correct element is the index of the value in label in the unique sorted array of labels that share the same value in Split_key.
The correct end result is shown here.
| Split_key | label | sub_label |
|---|---|---|
| A_B_C | 7 | A |
| A_B_C | 7 | A |
| A_B_C | 8 | B |
| A_B_C | 8 | B |
| A_B_C | 10 | C |
| A_B_C | 10 | C |
| D_E_F | 2 | D |
| D_E_F | 7 | E |
| D_E_F | 15 | F |
| G_H_I | 1 | G |
| G_H_I | 2 | H |
| G_H_I | 3 | I |
My initial attempt is very slow on large dataframes:
for i,row in bigframe.iterrows():
duplicates=bigframe[ bigframe["Split_key"]==row["Split_key"]]
if len(row["Split_key"].split("_"))<1:
continue
if len(duplicates)==1:
row["sub_label"]=row["Split_key"].split("_")[0]
else:
try:
shift=sorted(duplicates["label"].unique().astype(int)).index(int(row["label"]))
except:
shift=0
if (shift<len(row["Split_key"].split("_"))):
row["sub_label"]=row["Split_key"].split("_")[shift]
Is there any way to vectorize this code in python/pandas? I know using group / ungroup in R makes this possible from a previous post.