【问题标题】:How to iterate DataFrame of strings and apply if condtion over the result如何迭代字符串的DataFrame并在结果上应用条件
【发布时间】:2020-06-08 23:44:50
【问题描述】:

我正在尝试使用 if 条件迭代数据帧,以在字符串等于数据帧中第 i 个位置的字符串时返回一个值。

运行示例代码时出现以下错误

(`ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().`):
 df = {'step_ID':[1,1,2,2,3,3,4,4], 'step_name':['CC_Dchg', 'CC_Dchg', 'Rest', 'Rest', 'CC_Chg', 
    'CC_Chg', 'Rest', 'Rest']}
    df = pd.DataFrame(df)

    chg_step = []
    a = []

    for i in df:
        if df['step_name'] == 'CC_Chg':
            a = SiO_1['step_ID']
            chg_step = chg_step + a
        else:
            continue

检查df['step_name'] == 'CC_Chg' 是否为真的正确语法是什么?

【问题讨论】:

    标签: python string loops if-statement


    【解决方案1】:

    如果我理解正确,您需要step_name 等于给定值的行的step_ID。在 pandas 中,您不必编写自己的循环(或仅在极端情况下)。相反,这里有一个替代方案:

    # step by step
    
    # do the comparison step_name == X for each row.
    # The result is a boolean pandas Series
    mask = df['step_name'] == 'CC_Chg' 
    # The boolean pandas series can be used to select only some rows.
    # Then, we can retrieve the step_ID column for those rows only.
    # The result is again a pandas Series
    chg_step_series = df[mask].step_ID # this is a series
    # A pandas series can be converted to a numpy array using values,
    # and then a list by calling tolist()
    chg_step_series.values.tolist() # this is a list: [3,3]
    

    或者,在一行中:

    chg_step = df[df.step_name == 'CC_Chg'].step_ID.values.tolist()
    

    【讨论】:

    • 这太完美了,谢谢!我知道必须有更好的方法来做到这一点。
    • 不客气。请不要忘记将问题标记为已回答(我的答案左侧的勾号)。编码愉快!
    猜你喜欢
    • 1970-01-01
    • 2016-05-09
    • 2022-01-22
    • 2013-12-02
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 2016-06-09
    • 1970-01-01
    相关资源
    最近更新 更多