【问题标题】:loop through pandas dataframe to compare string if matches append row's value循环遍历熊猫数据框以比较字符串是否匹配追加行的值
【发布时间】:2021-08-08 17:54:44
【问题描述】:

我怎样才能实现以下目标?

mat_no grades
uJ/2018/001 A
uJ/2018/002 C
uJ/2018/003 B
uJ/2018/001 A
uJ/2018/003 C
uJ/2018/002 B
uJ/2018/001 D

以上是我的 python pandas 数据框,这是我的尝试:

result = [];
for stud in df_master: ## iterate through my dataframe
    if stud == "uj/2018/001": ## if matches; append the next value in the row
        result.append(stud)
    else:
        pass
print(result)

我的预期结果:

|:uJ/2018/001 |:A :  | :A  | :D|

或在列表中

uj/2018/001 ['A', 'A', 'D"]

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用布尔掩码和loc 访问器过滤结果,然后通过groupby()+cumcount() 然后pivot() 和最后reset_index() 跟踪位置:

    out=df.loc[df['mat_no'].eq("uJ/2018/001")]
    out['key']=out.groupby('mat_no').cumcount()
    out=out.pivot('mat_no','key','grades').rename_axis(columns=None).reset_index()
    

    out的输出:

        mat_no          0   1   2
    0   uJ/2018/001     A   A   D
    

    或

    如果需要列表格式,则使用query() 过滤掉结果,然后使用groupby()+agg():

    out=df.query("mat_no=='uJ/2018/001'").groupby('mat_no')['grades'].agg(list).reset_index()
    

    out 的输出:

        mat_no          grades
    0   uJ/2018/001     [A, A, D]
    

    【讨论】:

      【解决方案2】:

      您可以使用以下命令:

       my_output = df.query("mat_no=='uJ/2018/001'").groupby('mat_no')['grades'].agg(list).reset_index()
      

      【讨论】:

        猜你喜欢
        • 2020-11-20
        • 1970-01-01
        • 1970-01-01
        • 2017-06-08
        • 2017-01-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多