Is There a Simple Way to Change a Column of Yes/No to 1/0 in a Pandas Dataframe

Converting 'no' and 'yes' into 0 and 1 in pandas dataframe

You can also just use replace:

df.edjefe.replace(to_replace=['no', 'yes'], value=[0, 1])

Python - how to convert 1/0 to yes/no (in pandas.DataFrame)?

You can use pd.Series.map, which accepts a dictionary input:

import pandas as pd

df = pd.DataFrame({'alpha': [50, 51, 52], 'beta': [1,0,1]})

df['gamma'] = df['beta'].map({True: 'yes', False: 'no'})

Converting yes/no to integer type 1/0 (not just replacing) in Pandas data frame

astype returns a pandas series, it is not done in place. Use:

df["Inter Plan"] = df['Inter Plan'].replace({'no': 0, 'yes': 1}).astype(int)

There is a copy option for astype which will allow you to do the operation in place, but because you are using replace as well, I don't think you'll be able to do it all in one line, so it is probably best to just use the above piece of code. In addition, the in-place option (which is setting copy to False) comes with a warning:

be very careful setting copy=False as changes to values then may propagate to other pandas objects.

Setting 1 or 0 to new Pandas column conditionally

You could

In [231]: df['lunch'] = (df['hour']<=11) & (df['hour']<=1)

In [232]: df['lunch']
Out[232]:
0 True
1 True
2 True
3 False
4 False
Name: lunch, dtype: bool

In [233]: df['lunch'].astype(int)
Out[233]:
0 1
1 1
2 1
3 0
4 0
Name: lunch, dtype: int32


Related Topics



Leave a reply



Submit