gpt4 book ai didi

python - 循环中从数据帧获取最大值和最小值

转载 作者:太空宇宙 更新时间:2023-11-03 14:06:49 25 4
gpt4 key购买 nike

这是我的数据框中的列列表:

a=list(aps1)
a
Out[107]:
['ID',
'class',
'S3',
'S22',
'S23',
'S26_3',
'S28']

现在我正在尝试运行一个循环,该循环将获取每列的最大值和最小值并显示如下输出:

S3, Range in 0 to 100
S22, Range in 50 to 75

等等。对于循环,我使用了:

for columns in a:
print(columns + ', Range in ' + round(aps1.columns.min()) + ' to ' + round(aps1.columns.max()))

但我收到以下错误:

TypeError: can only concatenate list (not "str") to list

仅针对一个变量运行时:

print ('S23, Range in ' + round(aps1.S23.min()) + ' to ' + round(aps1.S23.max()))

我得到:

TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('<U21') dtype('<U21') dtype('<U21')

有人可以帮我吗?非常感谢。

最佳答案

使用格式:

for c in aps1.columns:
print ('{}, Range in {} to {}'.format(c, aps1[c].min(), round(aps1[c].max())))
<小时/>

但更好的是使用 aggregate对于具有 minmax 的 DataFrame:

aps1 = pd.DataFrame({'S3':[4,5,4,5,5,4],
'S22':[7,8,9,4,2,3],
'S23':[1,3,5,7,1,0],
'S26':[5,3,6,9,2,4]})

print (aps1)
S22 S23 S26 S3
0 7 1 5 4
1 8 3 3 5
2 9 5 6 4
3 4 7 9 5
4 2 1 2 5
5 3 0 4 4

df1 = aps1.agg(['min','max']).round()
print (df1)
S22 S23 S26 S3
min 2 0 2 4
max 9 7 9 5

for c in df1.columns:
print ('{}, Range in {} to {}'.format(c, s.loc['min', c], s.loc['max', c]))

S22, Range in 2 to 9
S23, Range in 0 to 7
S26, Range in 2 to 9
S3, Range in 4 to 5
<小时/>
for c in aps1.columns:
print ('{}, Range in {} to {}'.format(c, aps1[c].min(), round(aps1[c].max())))

S22, Range in 2 to 9
S23, Range in 0 to 7
S26, Range in 2 to 9
S3, Range in 4 to 5

关于python - 循环中从数据帧获取最大值和最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48823024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com