简体   繁体   中英

Why the Python for loop for agg func does not work?

Why the Python using loop for agg func does not work but the code above the for loop which is done for each element individually works

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

Looping is, most likely, never the best idea in pandas. Here is a pseudo answer, while not exactly your 'a' output, it will give you a df to play with that has the data.

# 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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