我正在尝试将数据集中“年龄”列下的负值转换为正值。因此,如果 Age = -15,则 Age_new = +15,否则如果 Age >=0,则 Age_new 仍为 Age。
我的原始数据框名为 df_no_mv。
所以我有以下代码:
def tran_neg_to_pos(df):
if df['Age'] < 0:
return df['Age'] * (-1)
elif df['Age'] >0:
return df['Age']
#create Age_new
df_no_mv['Age_new']=df_no_mv.apply(tran_neg_to_pos,axis=1)
df_no_mv
我看到根据上述逻辑成功创建了一个新列Age_new。但是我收到此警告消息:
C:\Users\Admin\anaconda3\lib\site-packages\ipykernel_launcher.py:20: SettingWithCopyWarning:
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
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
我该如何解决这个问题?
最佳答案
只需使用内置的 abs()
函数即可:
df_no_mv['Age_new'] = df_no_mv['Age'].abs()
这正如https://stackoverflow.com/a/29077254/1021819
引用号:https://pandas.pydata.org/pandas-docs/dev/reference/api/pandas.DataFrame.abs.html
FWIW,Python 内置有 abs()
。 numpy 也有它。
关于python - 将数据框中的负值转换为正值 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70692951/