0

I have a column in my dataframe like this:

  ___________________________
 |  columnn                  |
 ____________________________
 | [happiness#sad]           |
 | [happy ness#moderate]     |
 | [happie ness#sad]         |
 ____________________________

and I want to replace the “happy ness”,”happiness”,”happie ness” with 'happyness' . I am currently using this method but nothing is changed.

  string exactly matching 
  happy ness===> happyness
  happiness  ===> happyness
  happie ness===>happyness

I treid the below two approaches

1st Approach

   df['column']
   df.column=df.column.replace({"happiness":"happyness" ,"happy ness":"happyness" ,"happie ness":"happynesss" })

2nd Approach

   df['column']=df['column'].str.replace("happiness","happyness").replace(“happy ness”.”happyness”).replace(“happie ness”,”happynesss”) 

Desired Output:

           ______________________
          |  columnn             |
           _______________________
          | [happyness,sad]      |
          | [happyness,moderate] |
          | [happyness,sad]      |
          _______________________
2
  • your columns have list? Commented Jun 3, 2019 at 12:26
  • Yes I am having a list in a column Commented Jun 3, 2019 at 12:29

2 Answers 2

1

This is one approach using replace with regex=True.

Ex:

import pandas as pd

df = pd.DataFrame({"columnn": [["happiness#sad"], ["happy ness#moderate"], ["happie ness$sad"]]})
data = {"happiness":"happyness" ,"happy ness":"happyness" ,"happie ness":"happynesss" }
df["columnn"] = df["columnn"].apply(lambda x: pd.Series(x).replace(data, regex=True).tolist())
print(df)

Output:

                columnn
0       [happyness#sad]
1  [happyness#moderate]
2      [happynesss$sad]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Rakesh for helping out this issue
0

Try this approach i think this will work for you.

df['new_col']=df['column'].replace(to_replace = 
['happyness','happiness','happie ness'], value = 
['happyness','happyness','happyness'])

1 Comment

The above approach is not working @venkatadileep Thanks for your effort

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.