1

我需要用另一个值替换熊猫 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

我需要替换whatswhat iswhat‚Äô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但不是其他情况,结果不是熊猫 df,我需要它是熊猫 df。

4

1 回答 1

2

你得到的是一个 Pandas 系列,如果你想得到一个 DataFrame,只需使用

new_df = pd.DataFrame(df.log.str.replace("^whats", "what is").str.replace("^what’s", "what is"))

正如@Quang Hoang 所指出的,您可以使用 pandas OR 进行搜索并搜索whatsor 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

于 2021-02-09T19:26:06.597 回答