使用“函数”中的 "for loop" 打印 DataFrame 每一列的 Min/Max

Print Min/Max of each Columns of a DataFrame using a "for loop" in a "function

我知道这可能是一个愚蠢的问题,但我被卡住了:

df=[column names such as "Water", "Soil", "Fire"]
report=[]

def area():
   for i, col in enumerate(df.columns):
       max_col(i)= df[col].max()
       min_col(i)= df[col].min()
       balance(i)= max_col(i) + min_col(i)

       print(-------,col,------) # column name
       print(max_col(i))
       print(min_col(i))
       print(balance_col(i))

   return pd.DataFrame(report)

我收到此错误:SyntaxError: can't assign to function call 我想 display(print) 分别计算每列的值,并 return 通过新的 df 结果。非常感谢

使用这个:

# fake data
df = pd.DataFrame(np.array([[1, 2, 3, 1], [4, 5, 6,4], [7, 8, 9, 6]]),
                             columns=['a', 'b', 'c','d'])

def area(df):
   # define the output dataframe
   df_out= pd.DataFrame(columns=['col_name','max','min','balance'])
   for i, col in enumerate(df.columns):
       report=[]
       max_col= df[col].max()
       min_col= df[col].min()
       balance= max_col + min_col
       report.append(col) # column name
       report.append(max_col)
       report.append(min_col)
       report.append(balance)  
       df_out.loc[i] = report
   return df_out

area(df)

输出:

  col_name max min balance
0        a   7   1       8
1        b   8   2      10
2        c   9   3      12
3        d   6   1       7

您可以使用字典来存储 min_colmax_colbalance 的值,每个值都键入列名。然后将结果合并到 result 数据框中。

def area(df):
    min_col = {}
    max_col = {}
    balance = {}
    for col in df:
        max_col[col]= df[col].max()
        min_col[col]= df[col].min()
        balance[col]= max_col[col] + min_col[col]

    result = pd.DataFrame([min_col, max_col, balance], index=['min', 'max', 'balance'])
    return result

np.random.seed(0)
df = pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))
>>> df
          A         B         C
0  1.764052  0.400157  0.978738
1  2.240893  1.867558 -0.977278
2  0.950088 -0.151357 -0.103219
3  0.410599  0.144044  1.454274
4  0.761038  0.121675  0.443863

>>> area(df)
                A         B         C
min      0.410599 -0.151357 -0.977278
max      2.240893  1.867558  1.454274
balance  2.651492  1.716201  0.476996

您可以通过以下方式获得相同的结果:

df.apply(lambda s: pd.Series([s.min(), s.max(), s.max() + s.min()], 
                              index=['min', 'max', 'balance'])
)