如何用iloc重写这个表达式



我有一个表达式

df_1['result'][df_1['result'].isnull() & df_1['id'].notnull() ] = df_1['M'][df_1['result'].isnull() & df_1['id'].notnull()].apply(lambda x: [0]*len(x))

我得到了以下错误A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

我想把它重写成这样

df_1.iloc[:,'result'][df_1.iloc[:,result].isnull() & df_1.iloc[:,'id'].notnull()] = df_1.iloc[:,'M'][df_1.iloc[:,result].isnull() & df_1.iloc[:,'id'].notnull()].apply(lambda x: [0]*len(x))

我得到以下错误

only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

但是据我所知,我可以通过名称调用列,而不是通过索引

您应该使用loc:

df_1.loc[df_1['result'].isnull() & df_1['id'].notnull(), 'result'] = df_1.loc[df_1['result'].isnull() & df_1['id'].notnull(), 'M'].apply(lambda x: [0]*len(x))

或者如果这不起作用,在上面的行之前添加df_1 = df_1.copy()

最新更新