我需要用另一个值替换pandas df每行中的特定值。我的数据如下所示:
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
我需要替换whats
的是what is
,what’s
也应该是what is
。所需的输出:
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
我试过了:
new_df = df.log.str.replace("^whats", "what is").str.replace("^what’s", "what is")
这照顾whats
了其他情况,但没有解决,结果不是pandas df,我需要它是pandas df。
您得到的是熊猫系列,如果您想获取一个DataFrame,只需使用
new_df = pd.DataFrame(df.log.str.replace("^whats", "what is").str.replace("^what’s", "what is"))
正如@Quang Hoang指出的那样,您可以使用熊猫OR搜索并搜索whats
或what‚Äôs
:
new_df = pd.DataFrame(df.log.str.replace("^whats|what’s", "what is"))
完整代码:
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"))
结果是:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句