我知道这可能是一个愚蠢的问题,但我被困住了:
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_col
、max_col
和 balance
的值,每个值都以列名称为键。然后将结果合并到结果
数据框中。
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/