問題

我的資料看起來像這樣.如果'no_of_children'不是nan,我想用'Married'替換community_status 'Missing'.

 >cust_data_df[['marital_status','no_of_children']]
>

    marital_status  no_of_children

0   Married           NaN
1   Married           NaN
2   Missing            1
3   Missing            2
4   Single            NaN
5   Single            NaN
6   Married           NaN
7   Single            NaN
8   Married           NaN
9   Married           NaN
10  Single            NaN
 

這是我嘗試的:

 cust_data_df.loc[cust_data_df['no_of_children'].notna()==True, 'marital_status'].replace({'Missing':'Married'},inplace=True)
 

但這不是在做任何事情。

  最佳答案

分配後置替換的值以避免連結任務:

 m = cust_data_df['no_of_children'].notna()
d = {'Missing':'Married'}
cust_data_df.loc[m, 'marital_status'] = cust_data_df.loc[m, 'marital_status'].replace(d)
 

如果需要設定所有值:

 cust_data_df.loc[m, 'marital_status'] = 'Married'
 

編輯:

謝謝@Quickbeam2k1解釋:

CUST_data_df.loc [cust_data_df [‘no_of_children’].notna()== True,’community_status’]只是一個沒有引用的新物件.替換它,將原始物件保持不變

  相同標籤的其他問題

pythonpandas