Python changing values in dataframe after splitting

Viewed 54

My goal is to enter a 1 whenever a string in the 'SAD' column matches a column name, and 0 otherwise.

So we have this dataframe:

df = pd.DataFrame({'SAD': ['Game;Pool;Read;lol','Game;Read'], 'Game':[0,0], 'Pool': [0, 0], 'Read':[0, 0], 'Drink' : [0, 0]})

I have tried this: Splitting then assigning:

l= df["SAD"].apply(lambda x: x.split(";"))

for i in l:
   for x in i:
     if x in df.columns:
        df[x]=1
print(df)

However this replaced the entire dataframe with 1 at the first sight of a string that matches:

                        SAD  Game  Pool  Read  Drink
0        Game;Pool;Read;lol     1     1     1      0
1                 Game;Read     1     1     1      0

The desired output would be:

                            SAD  Game  Pool  Read  Drink
    0        Game;Pool;Read;lol     1     1     1      0
    1                 Game;Read     1     0     1      0
4 Answers
l= df["SAD"].apply(lambda x: x.split(";"))

for idx, i in enumerate(l):
   for x in i:
     if x in df.columns:
        df.loc[idx,x]=1
print(df)

Can you use .iloc for this:

import pandas as pd

df = pd.DataFrame({'SAD': ['Game;Pool;Read;lol','Game;Read'], 'Game':[0,0], 'Pool': [0, 0], 'Read':[0, 0], 'Drink' : [0, 0]})

l= df["SAD"].apply(lambda x: x.split(";"))

n=0
for i in l:
   for x in i:
     if x in df.columns:
        df[x].iloc[n]=1
   n += 1
print(df)

I think you can take a different approach to reduce the looping

cols = df.columns[1:].values
data= df['SAD'].map(lambda x: x.split(';')).map(lambda x: [1 if i in x else 0 for i in cols])
0    [1, 1, 1, 0]
1    [1, 0, 1, 0]

Then create the dataframe

df = pd.DataFrame(smp.tolist(), columns=cols).assign(SAD=df['SAD'])

   Game  Pool  Read  Drink                 SAD
0     1     1     1      0  Game;Pool;Read;lol
1     1     0     1      0           Game;Read

You can always reassign

A bit late to your repost but here is my code. It does the job but don't judge me for the messy code.

import pandas as pd
df = pd.DataFrame({'SAD': ['Game;Pool;Read;lol','Game;Read'], 'Game':[0,0], 'Pool': [0, 0], 'Read':[0, 0], 'Drink' : [0, 0]})

ColumnNames = df.columns.tolist()

l= df["SAD"].apply(lambda x: x.split(";"))
for row in range(0,len(df)):
    for check in l[row]:
        for checkvalue in range (0,len(ColumnNames)):
            if check == ColumnNames[checkvalue]:
                df.set_value(index=row, col=ColumnNames[checkvalue],value = 1)
Related