Python:如果两个单元格都包含某些字符串

时间:2019-07-19 03:24:20

标签: python dataframe

我有一个数据框:

                            name   alike
0  I love watermelon and banana.   melon
1  I love watermelon and banana.  banana
2                  I love melon.   melon
3                  I love grape.   grape

代码:

df.loc[df['name'].str.contains('watermelon'), 'alike'] = 'watermelon'
print(df)

输出:

                            name       alike
0  I love watermelon and banana.  watermelon
1  I love watermelon and banana.  watermelon
2                  I love melon.       melon
3                  I love grape.       grape

这不是我预期的结果,我只想在“名称”包含西瓜而“相同”包含“瓜果”时更改“相同”。

我已经尝试过这种方式:

df.loc[df['name'].str.contains('watermelon') and df['alike'].str.contains('melon'), 'alike'] = 'watermelon'
print(df)

错误说:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

1 个答案:

答案 0 :(得分:1)

use the bitwise & operator instead of and

function PageState(){
  let currentState = new homeState();

  this.change = function(state){
    currentState=state;
  }
}

const page = new PageState();

function homeState(){
  document.querySelector('.div').style.width = "100px";
}

或使用df.loc[df['name'].str.contains('watermelon') & df['alike'].str.contains('melon'), 'alike'] = 'watermelon'

apply(..., axis=1)
df = pd.DataFrame({
    "a": ["hello", "heello", "hello you"], 
    "b": ["haha", "hehe", "haha hehe"], 
    "c": ["yes", "yes", "yes"]
})

print(df)

df["c"] = df.apply(
    lambda row: row["c"] if "hello" in row["a"] and "hehe" in row["b"] else "no",
    axis=1)

print(df)

在您的情况下:

           a          b    c
0      hello       haha  yes
1     heello       hehe  yes
2  hello you  haha hehe  yes
           a          b    c
0      hello       haha   no
1     heello       hehe   no
2  hello you  haha hehe  yes