问题
在替换空值以使列成为布尔值的过程中,我们在fireplace_count
列中发现了空值。
如果fireplaceflag
值为False
,则fireplace_count
null
值应替换为0
为熊猫写的
df_train.loc[(df_train.fireplace_count.isnull()) & (df_train.fireplaceflag==False),'fireplace_count'] = 0
发布于 2019-07-23 06:07:36
我建议使用df.fillna()并将列名放在方法中以针对它,如下所示:
df['<column_name>']=df.<columnname>.fillna(<new_value>)
您可以将想要将空值更改为的新值放入括号中。在您的例子中,这是"0“。让我们也简化这个问题,因为None
值的条件似乎是如果有False
标志。
我将使用您之前发送给我的系列,但有一个小的更改。
import cudf
df = cudf.DataFrame({'basement_flag': [1, 1, 1, 0],
'basementsqft': [400,750,500,0],
'fireplace_count': [2, None, None, 1], #<-- added a None to illustrate the targeted nature of the solution
'fireplaceflag': [10, None, None, 8]})
print(df)
df['fireplace_count']=df.fireplace_count.fillna(0) #<-- This is the solution. It changes only the values in the column of interest, which is what you explained that you needed
print(df)
输出将为:
basement_flag basementsqft fireplace_count fireplaceflag
0 1 400 2 10
1 1 750
2 1 500
3 0 0 1 8
basement_flag basementsqft fireplace_count fireplaceflag
0 1 400 2 10
1 1 750 0
2 1 500 0
3 0 0 1 8
还有..。
df['fireplace_count'] = df['fireplace_count'].fillna(0)
df['fireplaceflag']= df['fireplaceflag'].fillna(-1)
df['fireplaceflag'] = df['fireplaceflag'].masked_assign(1, df['fireplace_count'] > 0)
这应该适用于任何基于我认为你的问题的奇怪情况(感谢Roy F@ NVIDIA)
如果这对你有效,或者你需要更多的帮助,请告诉我!
https://stackoverflow.com/questions/57153803
复制相似问题