1 回答
TA贡献1871条经验 获得超13个赞
您需要设置原始 df 的副本
print('df = \n', df)
def fn(df_fn):
cols = ['n_wheels', 'color', 'year']
# df_fn[cols][df_fn.fuel_type != 'gas'] = np.nan
df_fn.loc[df_fn.fuel_type != 'gas', cols] = np.nan
return df_fn
df1=df.copy()#I change here add copy
new_df = fn(df1)
print('df = \n', df)
print('new_df = \n', new_df)
df =
n_wheels color year fuel_type
0 2 red 2010 diesel
1 4 blue 1990 gas
2 4 red 1999 electric
df =
n_wheels color year fuel_type
0 2 red 2010 diesel
1 4 blue 1990 gas
2 4 red 1999 electric
new_df =
n_wheels color year fuel_type
0 NaN NaN NaN diesel
1 4.0 blue 1990.0 gas
2 NaN NaN NaN electric
添加回答
举报