Shivam
Shivam

Reputation: 243

How to change True/False with string in column in dataframe?

I am trying to convert True/False value in a particular column with some string value but it is not coming. How can i do? True/False are boolean.

Example:

df1:

col1  col2  col3
Ram   shyam True
axa   moh   False
sur   ami   True

Expected Output:

df:

col1  col2  col3
Ram   shyam right
axa   moh   False
sur   ami   right

Upvotes: 1

Views: 930

Answers (4)

David Jay Brady
David Jay Brady

Reputation: 1154

In case anyone wants to replace strings across multiple cols but not the whole dataframe, here's an example I didn't see in the docs

df[cols] = df[cols].replace({"old": "new"})

Upvotes: 0

Mayank Porwal
Mayank Porwal

Reputation: 34056

You can use a simple df.replace command like this:

In [1546]: df['col3'] = df['col3'].replace({True:'right'})
In [1547]: df
Out[1546]: 
  col1   col2   col3
0  Ram  shyam  right
1  axa    moh  False
2  sur    ami  right

Upvotes: 1

Jan
Jan

Reputation: 43169

You can use np.where:

import pandas as pd, numpy as np

dct = {"col1": ["Ram", "axa", "sur"],
       "col2": ["shyam", "moh", "ami"],
       "col3": [True, False, True]}
df1 = pd.DataFrame.from_dict(dct)

df1['col3'] = np.where(df1['col3'] == True, 'right', 'False')
print(df1)

This yields

  col1   col2   col3
0  Ram  shyam  right
1  axa    moh  False
2  sur    ami  right

Note that this changes the type of the column col3 from bool to object.

Upvotes: 2

Raj Srujan Jalem
Raj Srujan Jalem

Reputation: 661

Try this:

df["col3"] = df["col3"].apply(lambda x: "right" if x==True else False)

Upvotes: 0

Related Questions