python - 使用“函数”中的 "for loop"打印数据帧每列的最小值/最大值

标签 python arrays for-loop func

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

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:无法分配给函数调用 我想分别显示(打印)每列的计算值,并通过新的 df 返回结果。非常感谢

最佳答案

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

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'])
)

关于python - 使用“函数”中的 "for loop"打印数据帧每列的最小值/最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59162525/

相关文章:

python - 使用 python 文件启动 ipython notebook

python - 如何将 Odoo 中的菜单链接到计算的 URL

python - 从 token 列表生成所有可能的字符串

数组中只能有一个元素才能构成子数组吗?

c - 新手 : C syntax error when compiling

r - head() 函数在 'for' 循环中不起作用?

python - 停止执行 python 脚本

c# - C# 中的单字节数组到二维字节数组?

python - 创建与另一个相同大小的随机 numpy 矩阵。

java - 长循环计数器似乎效率很低