Making new columns from panda list

77 views Asked by At

Let's say i have a specific column in my data frame. Some of the fields contain only 1 value, but some even 10. I decided to split the column values by ';' separator.

data['golden_globes_nominee_categories'].str.split(';')

After that I iterated by row like this:

for index, row in data.iterrows():
    print (row['golden_globes_nominee_categories']) 

And got this:

['Best Original Song - Motion Picture ', ' Best Performance by an  Actor in a Motion Picture - Comedy or Musical']
['Best Original Score - Motion Picture ', ' Best Performance by an Actress in a Motion Picture - Drama']
...

Then I looped through each element like this:

for index, row in data.iterrows():
    for x in row['golden_globes_nominee_categories']:

But now I am really interested in how to create columns for every specific value which will contain the numbers (1 or 0) that will show me if it was mentioned in a cell?

Essentially I want to do something like this:

 dataframe["time_sp_comp2"] = dataframe["time_spend_company"].apply(lambda x: 1 if x==2 else 0)
 dataframe["time_sp_comp3"] = dataframe["time_spend_company"].apply(lambda x: 1 if x==3 else 0)
 dataframe["time_sp_comp4"] = dataframe["time_spend_company"].apply(lambda x: 1 if x==4 else 0)

 dataframe.drop('time_spend_company', axis=1, inplace=True)
1

There are 1 answers

0
Peter Leimbigler On

I think this is what you're after.

Example data

df = pd.DataFrame({'name': ['Jack', 'Jill', 'Chad'] , 
                   'tags': ['tall;rich;handsome', 
                            'short;rich;pretty',
                            'tall']})
df

   name                tags
0  Jack  tall;rich;handsome
1  Jill   short;rich;pretty
2  Chad                tall

Split tag strings, get dummy variables (you could do this with pd.get_dummies)

result = pd.DataFrame({k:1 for k in t} 
                      for t in df.tags.str.split(';')).fillna(0).astype(int)
result

   handsome  pretty  rich  short  tall
0         1       0     1      0     1
1         0       1     1      1     0
2         0       0     0      0     1

Merge names and dummy variables

pd.concat([df['name'], result], axis=1)

   name  handsome  pretty  rich  short  tall
0  Jack         1       0     1      0     1
1  Jill         0       1     1      1     0
2  Chad         0       0     0      0     1