简体   繁体   中英

Change row values in specific pandas data frame column with python

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM