Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split column list into rows without duplicating data

Tags:

python

pandas

I have a dataframe where the first column is a list, how can I iterate through the list and add a value to the relevant pre defined column:

workflow                cost      cam    gdp     ott    pdl
['cam', 'gdp', 'ott']   $2,346
['pdl', 'ott']          $1,200 

should convert to:

workflow                cost      cam    gdp     ott    pdl
['cam', 'gdp', 'ott']   $2,346    782    782     782
['pdl', 'ott']          $1,200                   600    600

I can get the length of the list, but I can't work out how to iterate over the list in order to match it to a column heading. Basically the cost is simply split evenly between the number of processes in the list.

like image 765
iFunction Avatar asked Jul 20 '26 06:07

iFunction


1 Answers

Another alternative:

df1 = (
    df.assign(cost=
        df["cost"].str.replace(r"\$|,", "", regex=True).astype("float")
        / df["workflow"].str.len()
    )
    .explode("workflow")
    .pivot(columns="workflow", values="cost")
)
df = pd.concat([df[["workflow", "cost"]], df1], axis=1)

Result for the sample:

          workflow    cost    cam    gdp    ott    pdl
0  [cam, gdp, ott]  $2,346  782.0  782.0  782.0    NaN
1       [pdl, ott]  $1,200    NaN    NaN  600.0  600.0
like image 193
Timus Avatar answered Jul 22 '26 18:07

Timus