I have a DataFrame
with 1mln of rows and two columns Type
and Name
whose values are a lists with non-unique values. Both Type
and Name
columns have the same number of elements because they form a pair (Type
, Name
). I would like to add to my DataFrame
columns whose names are the unique types from Type
column with the values being a list of corresponding values from Name
columns. Below is a short example of the current code. It works but very slow when the number of rows is 1mln so I'm looking for a faster solution.
import pandas as pd
df = pd.DataFrame({"Type": [["1", "1", "2", "3"], ["2","3"]], "Name": [["A", "B", "C", "D"], ["E", "F"]]})
unique = list(set(df["Type"].explode()))
for t in unique:
df[t] = None
df[t] = df[t].astype('object')
for idx, row in df.iterrows():
for t in unique:
df.at[idx, t] = [row["Name"][i] for i in range(len(row["Name"])) if row["Type"][i] == t]