使用 python 更改特定 Pandas 数据框列中的行值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44877874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:33:28  来源:igfitidea点击:

Change row values in specific pandas data frame column with python

pythonpandasdataframe

提问by Saibottrenham

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.

目标是将每个列行匹配的值从 0 更改为 1。

    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.

我对 Pandas 文档以及谷歌和堆栈溢出做了一些深入的研究,但似乎没有合适的解决方案来解决这个问题。

As always any help is much appreciated.

与往常一样,非常感谢任何帮助。

回答by Allen

You can simply use loc and set values:

您可以简单地使用 loc 并设置值:

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