Reputation: 1530
I need to replace the specific values in every row of pandas df with another value. My data looks like this:
time log
1 whats the weather look like today
2 what is the weather look like today
3 whats for lunch
4 what’s for lunch
I need to replace whats
to be what is
and what’s
to be what is
also.
The desired output:
time log
1 what is the weather look like today
2 what is the weather look like today
3 what is for lunch
4 what is for lunch
I have tried:
new_df = df.log.str.replace("^whats", "what is").str.replace("^what’s", "what is")
This took care of whats
but not the other case and the outcome is not a pandas df and I need it to be pandas df.
Upvotes: 1
Views: 615
Reputation: 2508
What you are getting is a Pandas Series, if you want to get a DataFrame, just use
new_df = pd.DataFrame(df.log.str.replace("^whats", "what is").str.replace("^what’s", "what is"))
And as was pointed out by @Quang Hoang, you can search using the pandas OR and search either for whats
or what’s
:
new_df = pd.DataFrame(df.log.str.replace("^whats|what’s", "what is"))
Full code:
import pandas as pd
df = pd.DataFrame({"time": [1,2,3,4],
"log": ['whats the weather look like today', 'what is the weather look like today', 'whats for lunch', 'what’s for lunch']
})
new_df = pd.DataFrame(df.log.str.replace("^whats", "what is").str.replace("^what’s", "what is"))
and the results are:
print(df)
time log
0 1 whats the weather look like today
1 2 what is the weather look like today
2 3 whats for lunch
3 4 what’s for lunch
print(new_df)
log
0 what is the weather look like today
1 what is the weather look like today
2 what is for lunch
3 what is for lunch
Upvotes: 2