2

I am trying to transform the negative values under the 'Age' column in my dataset to positive values. So if Age = -15, then Age_new = +15, else if Age >=0, then Age_new remains as Age.

My orginal dataframe is called df_no_mv.

So I have the following code:

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

I see that a new column Age_new is successfully created according to above logic. However I get this warning message:


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

How can I fix this?

jtlz2
  • 7,700
  • 9
  • 64
  • 114
mint
  • 21
  • 2

2 Answers2

3

Just use the built-in abs() function:

df_no_mv['Age_new'] = df_no_mv['Age'].abs()

This is just as per https://stackoverflow.com/a/29077254/1021819

REF: https://pandas.pydata.org/pandas-docs/dev/reference/api/pandas.DataFrame.abs.html

FWIW, python has abs() at the built-in level. numpy also has it.

jtlz2
  • 7,700
  • 9
  • 64
  • 114
  • I switched to using abs() but got the same warning message. Additionally the last statement in the warning message is new: – mint Jan 13 '22 at 07:57
  • C:\Users\Admin\anaconda3\lib\site-packages\ipykernel_launcher.py:1: 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 """Entry point for launching an IPython kernel. – mint Jan 13 '22 at 07:58
  • Indeed - the question was "How can I fix this?" - my solution to that question is to not use that approach at all. Or are you saying the error still arises even then? – jtlz2 Jan 13 '22 at 08:01
  • I am looking for a way to transform my dataset without getting the warning error. Using abs() transforms the data but then i still have the warning message. – mint Jan 13 '22 at 08:06
0

Pandas series have .abs(), so:

df_no_mv['Age_new']=df_no_mv['Age'].abs()
jtlz2
  • 7,700
  • 9
  • 64
  • 114
AKX
  • 152,115
  • 15
  • 115
  • 172