替换字符串数据帧熊猫中的第一个值

时间:2021-02-09 19:11:07

标签: python pandas dataframe replace pd

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

1 个答案:

答案 0 :(得分:2)

你得到的是一个Pandas Series,如果你想得到一个DataFrame,就用

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

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