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
Python - Passing a Function into Another Function
Difference Between the Built-In Pow() and Math.Pow() for Floats, in Python
How to Add Timezone into a Naive Datetime Instance in Python
Sqlalchemy: Unexpected Results When Using 'And' and 'Or'
How to Redirect the Output of Print to a Txt File
How to Make Custom Legend in Matplotlib
Python Requests Ssl Error - Certificate Verify Failed
Conversion of Strings Like \\Uxxxx in Python
How to Escape Latex Code Received Through User Input
How to Use a (Random) *.Otf or *.Ttf Font in Matplotlib
How to Install Pip for Python 3 on MAC Os X
Why Use Os.Path.Join Over String Concatenation
How to Stack Vectors of Different Lengths in Numpy
How to Rotate Selenium Webrowser Ip Address
Generate Permutations of List with Repeated Elements
How to Force a List to a Fixed Size
How to Find First Non-Zero Value in Every Column of a Numpy Array