pandas 如何替换熊猫数据框中的列的选定行的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47953338/
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-09-14 04:57:14  来源:igfitidea点击:

how to replace values of selected row of a column in panda's dataframe?

pythonpandasmachine-learninganaconda

提问by Bilal Butt

i have train dataset which has 12 columns. enter image description here

我有 12 列的训练数据集。 在此处输入图片说明

I want to select Cabincolumn rows according to Pclasscolumn's value 1. And then replace value of selected rows of Cabin column with 1.

我想根据Pclass列的值 1选择Cabin列行。然后将 Cabin 列的选定行的值替换为 1。

i did following code but it replace all values of cabin column with 1 even NaN values replace by 1.How i can replace only selected rows?

我做了下面的代码,但它用 1 替换了小屋列的所有值,甚至将 NaN 值替换为 1。如何只替换选定的行?

train['Cabin'] =train[train['Pclass']==1]['Cabin']=1

回答by jezrael

You can select by locwith condition rows of column Cabinand set to scalar:

您可以loc根据列的条件行进行选择Cabin并设置为标量:

train.loc[train['Pclass'] == 1, 'Cabin'] = 1

And your code replace all values to 1because is is same as:

并且您的代码将所有值替换为1因为与以下内容相同:

train['Cabin'] = 1

Sample:

样品

train = pd.DataFrame({'Pclass':[1,2,3,1,2],
                      'Cabin':[10,20,30,40,50]})
print (train)
   Cabin  Pclass
0     10       1
1     20       2
2     30       3
3     40       1
4     50       2

train.loc[train['Pclass'] == 1, 'Cabin'] = 1
print (train)
   Cabin  Pclass
0      1       1
1     20       2
2     30       3
3      1       1
4     50       2