【问题标题】:Print Min/Max of each Columns of a DataFrame using a "for loop" in a "function使用“函数”中的“for循环”打印DataFrame每列的最小值/最大值
【发布时间】:2020-03-28 11:01:25
【问题描述】:

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

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)分别计算每列的值,并通过新的df返回结果。非常感谢

【问题讨论】:

  • 可以添加一些数据吗?
  • 什么是max_colmin_colbalance?它们是函数吗?如果是这样,那么您能解释一下您要做什么,因为就像错误消息所说的那样,您不能为函数调用的结果赋值。
  • 不,它们只是每列的最小值和最大值。它们是浮点数或整数。

标签: python arrays for-loop func


【解决方案1】:

您可以使用字典来存储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'])
)

【讨论】:

  • 不需要字典 IMO。我的答案建立在 OP 代码之上并完成了这项工作
【解决方案2】:

使用这个:

# 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

【讨论】:

  • 谢谢。但是你从来没有在你的代码中使用过 i!
  • 查看我的更新答案。对于这个简单的任务,另一个答案似乎太复杂了
  • 谢谢你。
猜你喜欢
  • 2016-10-06
  • 1970-01-01
  • 2018-09-21
  • 1970-01-01
  • 1970-01-01
  • 2019-09-18
  • 2013-09-30
  • 2012-01-16
  • 2018-09-05
相关资源
最近更新 更多