Leockl
Leockl

Reputation: 2156

How to create a new column from an existing column in a pandas dataframe

I have the following pandas dataframe:

df = pd.DataFrame([-0.167085, 0.009688, -0.034906, -2.393235, 1.006652], 
                   index=['a', 'b', 'c', 'd', 'e'], 
                   columns=['Feature Importances'])

Output:

df - create new col

Without having to use any loops, what is the best way to create a new column (say called Difference from 0) where the values in this new Difference from 0 column are the distances from 0 for each of the Feature Importances values. For eg. for a, Difference from 0 value would be 0 - (-0.167085) = 0.167085, for e, Difference from 0 value would be 1.006652 - 0 = 1.006652, etc.

Many thanks in advance.

Upvotes: 0

Views: 70

Answers (2)

Joe Ferndz
Joe Ferndz

Reputation: 8508

Looks like you want to find the difference from zero and also get the absolute value.

This should give you the results.

df['Diff']  = df['Feature Importances'].abs() - 0

   Feature Importances      Diff
a            -0.167085  0.167085
b             0.009688  0.009688
c            -0.034906  0.034906
d            -2.393235  2.393235
e             1.006652  1.006652

Upvotes: 1

anon01
anon01

Reputation: 11161

assign a column that operates as the absolute value on the feature importance column:

df["Difference from 0"] = df["Feature Importances"].abs()

Upvotes: 2

Related Questions