【问题标题】:how to set value in 2 cell if other cell contains 'something'如果其他单元格包含“某物”,如何在 2 个单元格中设置值
【发布时间】:2018-06-24 15:10:32
【问题描述】:

我有一些熊猫数据框:

a,b,c
AAA,,
DDD,,
KKK,,
AAA,,  

我想在“A”列中搜索,如果“A”列中的字符串包含单词“AAA”,我需要在“B”列中设置值“BBB”,在“C”列中设置值“CCC”。
所以,我想得到如下结果:

a,b,c
AAA,BBB,CCC
DDD,,
KKK,,
AAA,BBB,CCC

我用numpy写了代码:

df['b'] = pd.np.where(df.a.str.contains("AAA"), "BBB", '')

如何扩展它以使用 'b' 和 'c' 列?

【问题讨论】:

    标签: python python-3.x pandas numpy dataframe


    【解决方案1】:

    你可以使用双np.where:

    mask = df.a.str.contains("AAA")
    df['b'] = pd.np.where(mask, "BBB", '')
    df['c'] = pd.np.where(mask, "CCC", '')
    

    assign:

    mask = df.a.str.contains("AAA")
    df = df.assign(b=pd.np.where(mask, "BBB", ''), c=pd.np.where(mask, "CCC", ''))
    

    如果需要使用一个np.where 创建多个列,则需要创建Nx1 掩码:

    mask = df.a.str.contains("AAA")[:, None]
    df[['b','c']] = np.where(mask, ['BBB','CCC'], ['',''])
    print (df)
         a    b    c
    0  AAA  BBB  CCC
    1  DDD          
    2  KKK          
    3  AAA  BBB  CCC
    

    【讨论】:

    • 如果我想在字符串中搜索 2 个或更多变体,我应该改变什么?例如“AAA”或“DDD”或“KKK”?
    • @j.stalin - 你认为mask = df.a.str.contains("AAA|DDD|KKK") 吗?
    • 再次感谢,这正是我需要的
    • 还有一个问题,如何更改我需要的单元格而不更改其他单元格?我
    • @j.stalin - 我认为需要df = df.assign(b=pd.np.where(mask, "BBB", df.a), c=pd.np.where(mask, "CCC", df.a))
    猜你喜欢
    • 2018-01-20
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多