A.DS
A.DS

Reputation: 246

Changing positive(+) and negative(-) signs to integers in python

I have a dataframe with the following column:

A
+
+
-
+
-

How do I convert this column into integer values. So that I could multiply it to other numerical values?

Therefore, all '+' would be replaced by 1 and '-' by -1.

Upvotes: 5

Views: 1360

Answers (5)

piRSquared
piRSquared

Reputation: 294258

searchsorted

df.assign(A=1 - np.array(['+']).searchsorted(df.A) * 2)

   A
0  1
1  1
2 -1
3  1
4 -1

Succinct

df.assign(A=df.A.eq('-').mul(2).rsub(1))

   A
0  1
1  1
2 -1
3  1
4 -1

Upvotes: 3

Haleemur Ali
Haleemur Ali

Reputation: 28253

using apply:

assumes that only + and - values are in the column

df['A'] = df.A.apply(lambda x: 1 if x == '+' else -1)

using string concatenation & casting:

df['A'] = (df.A + '1').astype(int)

using string equality & casting:

df['A'] = (df.A == '+').astype(int)*2-1

Upvotes: 7

niraj
niraj

Reputation: 18208

Some possible ways may be using add to add string of 1 and converting to int with astype :

df['A'] = df.A.add('1').astype(int)

Or using lambda for same purpose as above:

df['A'] = df.A.apply(lambda row: int(row + '1'))

Upvotes: 3

llllllllll
llllllllll

Reputation: 16404

You can use:

df.A = df.A.map({'+': 1, '-': -1})

Upvotes: 10

sacuL
sacuL

Reputation: 51335

If I understand correctly, you could just use replace:

>>> df
   A
0  +
1  +
2  -
3  +
4  -

new_df = df.replace({'A':{'+':1, '-':-1}})

>>> new_df
   A
0  1
1  1
2 -1
3  1
4 -1

Upvotes: 7

Related Questions