Reputation: 246
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
Reputation: 294258
searchsorted
df.assign(A=1 - np.array(['+']).searchsorted(df.A) * 2)
A
0 1
1 1
2 -1
3 1
4 -1
df.assign(A=df.A.eq('-').mul(2).rsub(1))
A
0 1
1 1
2 -1
3 1
4 -1
Upvotes: 3
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
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