Reputation: 28905
I have a column of positive and negative numbers and I want to convert it to a list of 0s and 1s. If the number if positive, it should be replaced with a 1. If the number is negative or 0, it should be replaced by a 0. How can I do this?
For example, in R, I would do:
list = ifelse(list > 0, 1, 0)
Upvotes: 0
Views: 313
Reputation: 926
You can use DataFrame.apply
to apply a function to each row of your DataFrame. For instance:
import numpy as np
import pandas as pd
df = pd.DataFrame({'A': [1, -2, 3, -4]})
df['A'] = df.apply(lambda row:np.where(row['A'] > 0, 1, 0), axis=1)
The lambda
function can be replaced with any function (doesn't have to be a lambda
), and axis=1
is to apply the function to each row rather than each column.
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html
Upvotes: 0
Reputation: 6579
You can return boolean
values and use astype(int)
to convert them to 1
and 0
.
print((df['A'] > 0).astype(int))
Example:
df = pd.DataFrame({'A': [1,-1,2,-2,3,-3]})
print(df)
A
0 1
1 -1
2 2
3 -2
4 3
5 -3
print((df['A'] > 0).astype(int))
0 1
1 0
2 1
3 0
4 1
5 0
Upvotes: 1
Reputation: 17152
you can use an indexer and .loc to change values such has
indexer = df[df['col']>0].index
df.loc[indexer] = 1
indexer_2 = df[df['col']<0].index
df.loc[indexer_2] = 0
or you can look at numpy.where such has
import numpy as np
import pandas as pd
pd.DataFrame(np.where(df>0,1,0),index=df.index)
Upvotes: 0