簡體   English   中英

使用python更改特定pandas數據框列中的行值

[英]Change row values in specific pandas data frame column with python

以下問題。

我有一個具有以下格式的數據框。

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

此外,我有一個與列名匹配的值列表:

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

目標是將每個列匹配的值0更改為1。

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

我對Pandas文檔以及google和堆棧溢出做了一些深入的研究,但似乎沒有適合這個問題的解決方案。

一如往常,任何幫助都非常感謝。

您只需使用loc和set值:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM