【问题标题】:How to populate a column in a df based on conditions in Python如何根据 Python 中的条件填充 df 中的列
【发布时间】:2023-01-31 18:56:02
【问题描述】:

我是编程新手并且自学成才,所以请原谅我有限的知识。

我有一个看起来像这样的 df:

df1= pd.DataFrame.from_dict({
    'Description': ['This car is german', 'This vehicle is french', 'This automobile is british', 'This car is british', 'This thing is british'], 
    'SUV?': ['Yes', 'No', 'No', 'Yes', 'Yes'],
    'Action': [' ', ' ', ' ', ' ', ' '],
    })
df1

我想做的是,如果“描述”列中出现“英国”一词并且“SUV”列中出现“是”一词,则用字符串“购买”填充“操作”列。

我尝试使用 lambda 函数,但我只能让它在其中一个条件下工作。例如:df1["Action"] = df1['Description'].apply(lambda x: "Buy" if "british" in x else "0")

如果有人能走上正轨,我将不胜感激!

【问题讨论】:

    标签: python if-statement


    【解决方案1】:

    您可以使用 pandas DataFrame 查询方法来检查多个条件。查询方法采用包含要检查的条件的字符串参数。下面是一个示例,说明如果满足两个条件,如何使用查询方法用字符串“购买”填充“操作”列:

    import pandas as pd
    
    df1 = pd.DataFrame.from_dict({
     'Description': ['This car is german', 'This vehicle is french', 'This automobile is british', 'This car is british', 'This thing is british'], 
     'SUV?': ['Yes', 'No', 'No', 'Yes', 'Yes'], 
     'Action': [' ', ' ', ' ', ' ', ' '],
    })
    
    df1.query('Description.str.contains("british") and SUV? == "Yes"', inplace=True)
    df1['Action'] = 'buy'
    
    print(df1)
    

    这将输出以下 DataFrame,其中“Action”列填充了字符串“buy”:

    Description SUV?    Action
    This car is british Yes buy
    This automobile is british  Yes buy
    This thing is british   Yes buy
    

    【讨论】:

      【解决方案2】:

      例如你可以使用np.where()

      import numpy as np
      
      df1["Action"] = np.where(df1["Description"].str.contains('british'), 1, 0)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-14
        • 1970-01-01
        • 2020-12-29
        • 2021-07-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多