Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert all numeric columns of dataframe to absolute value

Tags:

python

pandas

I want to convert all numeric columns in a dataframe to their absolute values and am doing this:

df = df.abs()

However, it gives the error:

*** TypeError: bad operand type for abs(): 'unicode'

How to fix this? I would really prefer not having to manually specify the column names

like image 695
user308827 Avatar asked Mar 28 '16 23:03

user308827


People also ask

How do you take the absolute value of all the values in a DataFrame?

abs() is one of the simplest pandas dataframe function. It returns an object with absolute value taken and it is only applicable to objects that are all numeric. It does not work with any Nan value either. abs() function can also be used with complex numbers to find their absolute value.

How do I make an absolute value column in pandas?

Pandas absolute value of columnThe abs() function is used to get a Series/DataFrame with absolute numeric value of each element. This function only applies to elements that are all numeric. Returns: Series/DataFrame containing the absolute value of each element.

How do you make all values positive in a data frame?

This can be done by using abs function. For example, if we have a data frame df with many columns and each of them having some negative values then those values can be converted to positive values by just using abs(df).


2 Answers

You could use np.issubdtype to check whether your dtype of the columns is np.number or not with apply. Using @Amy Tavory example:

df = pd.DataFrame({'a': ['-1', '2'], 'b': [-1, 2]})
res = df.apply(lambda x: x.abs() if np.issubdtype(x.dtype, np.number) else x)

In [14]: res
Out[14]:
    a  b
0  -1  1
1   2  2

Or you could use np.dtype.kind to check whether your dtype is numeric:

res1 = df.apply(lambda x: x.abs() if x.dtype.kind in 'iufc' else x)


In [20]: res1
Out[20]:
    a  b
0  -1  1
1   2  2

Note: You may be also interested in NumPy dtype hierarchy

like image 177
Anton Protopopov Avatar answered Oct 02 '22 23:10

Anton Protopopov


Borrowing from an answer to this question, how about selecting the columns that are numeric?

Say you start with

df = pd.DataFrame({'a': ['-1', '2'], 'b': [-1, 2]})
>>> df        
    a   b
0   -1  -1
1   2   2

Then just do

numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
for c in [c for c in df.columns if df[c].dtype in numerics]:
    df[c] = df[c].abs()
>>> df
    a   b
0   -1  1
1   2   2
like image 38
Ami Tavory Avatar answered Oct 02 '22 23:10

Ami Tavory