[英]replace the first value in a string dataframe pandas
I need to replace the specific values in every row of pandas df with another value.我需要用另一个值替换 pandas df 每一行中的特定值。 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.我需要替换
whats
to be what is
and what, what’s
to be what is
also。 The desired output:所需的 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.这解决了问题,但没有解决其他情况,结果不是
whats
df,我需要它是 pandas df。
What you are getting is a Pandas Series, if you want to get a DataFrame, just use您得到的是 Pandas 系列,如果您想获得 DataFrame,只需使用
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
:正如@Quang Hoang 所指出的,您可以使用 pandas OR 进行搜索,然后搜索
whats
或 what, 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.