8

Following problem.

I have a data frame with the following format.

   Col1 Col2 Col3 Col4  
1    0    0    0    0
2    0    0    0    0

Furthermore, I have a List of values that match the column names:

ColNameList1 = [Col1, Col3] #list for the first row
ColNameList2 = [Col3, Col4] #list for the second row

The target is to change the value of 0 to 1 for every column row match.

    Col1 Col2 Col3 Col4  
1    1    0    1    0 
2    0    0    1    1

I did some intense research on the Pandas documentation and also google and stack overflow but it seems there is not a fitting solution for this problem.

As always any help is much appreciated.

1 Answer 1

20

You can simply use loc and set values:

df.loc[1,ColNameList1]=1

df.loc[2,ColNameList2]=1

df
Out[10]: 
   Col1  Col2  Col3  Col4
1     1     0     1     0
2     0     0     1     1
Sign up to request clarification or add additional context in comments.

5 Comments

thanks for the prompt reply, I got the error AttributeError: 'int' object has no attribute 'loc'. Do I miss something?
That's strange. Is your df actually a pandas dataframe? Can you show the complete error stack trace?. Can you also do a df.head()?
you should check the data type of your data frame it seems to be some problem.
pandas version 0.19.2 df = pd.DataFrame() df['Col1'] = [0, 0] df['Col2'] = [0, 0] df['Col3'] = [0, 0] df['Col4'] = [0, 0] print df print type(df) ColNameList1 = ['Col1', 'Col3'] #list for the first row ColNameList2 = ['Col3', 'Col4'] #list for the second row df = df.loc[1,ColNameList2]=1 print df when I run this code i get ` Col1 Col2 Col3 Col4 0 0 0 0 0 1 0 0 0 0 <class 'pandas.core.frame.DataFrame'> AttributeError: 'int' object has no attribute 'loc' `
2 problems: a:) You can't do df = df.loc[1,ColNameList2]=1, just do df.loc[1,ColNameList2]=1. b:) In your example data, the df index is 1 based here it appears to be 0 based. If it's 0 based, you need to use df.loc[0] and df.loc[1] respectively.

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.