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
how to replace values of selected row of a column in panda's dataframe?
提问by Bilal Butt
i have train dataset which has 12 columns.
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 loc
with condition rows of column Cabin
and set to scalar:
您可以loc
根据列的条件行进行选择Cabin
并设置为标量:
train.loc[train['Pclass'] == 1, 'Cabin'] = 1
And your code replace all values to 1
because 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