繁体   English   中英

为什么 agg func 的 Python for 循环不起作用?

[英]Why the Python for loop for agg func does not work?

为什么使用 agg func 的循环的 Python 不起作用,但为每个元素单独完成的 for 循环上方的代码可以工作

test = pd.DataFrame([[1, 2, 3],
                       [4, 5, 6],
                       [7, 8, 9],
                       [10,11,12]],
                      columns=['A', 'B', 'C'])
    
    cols=['A', 'B', 'C']
    
    a=[]
    
    #a.append(test.agg(**{'A'+'_sum' : ('A','sum'), 'A'+'_min' : ('A','min'), 'A' + "_max" : ('A', "max"), 'A' + "_mean" : ('A', "mean")}))
    
    #a.append(test.agg(**{'B'+'_sum' : ('B','sum'), 'B'+'_min' : ('B','min'), 'B' + "_max" : ('B', "max"), 'B' + "_mean" : ('B', "mean")}))
    
    #a.append(test.agg(**{'C'+'_sum' : ('C','sum'), 'C'+'_min' : ('C','min'), 'C' + "_max" : ('C', "max"), 'C' + "_mean" : ('C', "mean")}))
    
    for col in cols:
    
          a.append(test.agg(**{col + "_first" : (col, "first"),
    
                col + "_min" : (col, "min"),
    
                col + "_max" : (col, "max"),
    
                col + "_mean" : (col, "mean")
                }
            )
        )
    
    a

在 pandas 中,循环很可能永远不是最好的主意。 这是一个伪答案,虽然不完全是你的“a”输出,但它会给你一个 df 来玩,它有数据。

# Describe will give you most of your desired data.
desc_df = test.describe()
# Create a summed df to use with .concat()
sum_df = pd.DataFrame([test.sum(axis=0)])
# Name the row.
sum_df.index = ['sum']
# Concat them.
final_df = pd.concat([desc_df, sum_df])
# Example to a different type, since yours was a list.
final_df.to_dict()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM