3

I have a series y in Python with values Accepted and Rejected. I want to create a new dataframe with value 1 for Accepted and 0 for Rejected.

I'm trying to loop through the values of y and write to a new df dummy. My progress so far is

dummy=pd.DataFrame()
i=0

for i in range(0,len(y)):
    if y[i]=='Approved': 
        dummy[i:]==1
    else: 
        dummy[i:]==0

but I got a feeling that I'm off track. Can anyone help me out?

The series y looks like this:

   y
Accepted
Rejected
Accepted
Accepted
Accepted

The desired output should be something like

dummy
  1
  0
  1
  1
  1

2 Answers 2

3

Here loop is not necessary, because slow. Better is convert boolean mask to True/False to 0,1 by converting to integers or use numpy.where:

df['dummy'] =  (df['y']=='Approved').astype(int)

df['dummy'] =  np.where(df['y']=='Approved', 1, 0)

Your solution should be changed (loopy slow solution):

print (df)

0  Accepted
1  Rejected
2  Accepted
3  Accepted
4  Accepted

out = []
for i in range(0,len(df)):
    if df.loc[i, 'y']=='Accepted': 
        out.append(1)
    else: 
        out.append(0)

print (out)
[1, 0, 1, 1, 1]

df['dummy'] = out
print (df)
          y  dummy
0  Accepted      1
1  Rejected      0
2  Accepted      1
3  Accepted      1
4  Accepted      1
Sign up to request clarification or add additional context in comments.

1 Comment

@Artem - yes, added to answer.
1

you can use:

df['dummy'] = df.y.apply(lambda x:  1 if  x == 'Accepted' else 0)

if you want to use a for loop:

new_dummy_data = []

for value in df.y.values:
    if value == 'Accepted':
        new_dummy_data.append(1)
    else:
        new_dummy_data.append(0)

df['dummy'] = new_dummy_data

2 Comments

apply is loop under the hood ;)
yep, but not in the way the OP wants, I mean a visible for loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.