1

So I need to understand the direction of all the values in a dataframe and if negative multiply with -1

if I start with

num = df._get_numeric_data()
an then
if num[num < 0]: 
    num= num* -1

Is that in any way correct?

Viktor Mellgren
  • 4,318
  • 3
  • 42
  • 75
  • kindly provide dataset and format ur request properly. https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples – sammywemmy Mar 03 '20 at 11:03

2 Answers2

2

Use DataFrame.select_dtypes for numeric columns and then add DataFrame.abs:

df = pd.DataFrame({
        'A':list('abcdef'),
         'B':[4,-5,4,5,5,4],
         'C':[7,-8,9,4,2,-3],
         'D':[1,-3,5,7,1,0],
         'E':[5,3,6,9,-2,4],
         'F':list('aaabbb')
})

cols = df.select_dtypes(np.number).columns
df[cols] = df[cols].abs()
print (df)
   A  B  C  D  E  F
0  a  4  7  1  5  a
1  b  5  8  3  3  a
2  c  4  9  5  6  a
3  d  5  4  7  9  b
4  e  5  2  1  2  b
5  f  4  3  0  4  b

So solution is same like multiple by -1 only negative values:

cols = df.select_dtypes(np.number).columns
df[cols] = df[cols].mask(df[cols] < 0, df[cols] * -1)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0

If you need all numbers to be positive you could just use the abs function

FabZanna
  • 181
  • 1
  • 10