gpt4 book ai didi

python - 如何为所选列选择一行中的最大值和最小值

转载 作者:太空狗 更新时间:2023-10-29 22:25:07 25 4
gpt4 key购买 nike

假设我们有下表 enter image description here

我想找到一组特定列的每一行的最大值和最小值(假设 CENSUS2010POP、ESTIMATESBASE1010、POPESTIMATE2010)。如何用 Pandas 做到这一点?

最佳答案

我想你需要minmax :

df_subset=df.set_index('CTYNAME')[['CENSUS2010POP', 'ESTIMATESBASE1010', 'POPESTIMATE2010']]
df1 = df_subset.min(axis=1)
print (df1)

df2= df_subset.max(axis=1)
print (df2)

编辑:

df = pd.DataFrame({'CTYNAME':['Alabama','Autauga County','Baldwin County','Barbour County'],
'CENSUS2010POP':[4,5,6,2],
'ESTIMATESBASE1010':[7,8,9,3],
'POPESTIMATE2010':[1,3,5,5]})

print (df)
CENSUS2010POP CTYNAME ESTIMATESBASE1010 POPESTIMATE2010
0 4 Alabama 7 1
1 5 Autauga County 8 3
2 6 Baldwin County 9 5
3 2 Barbour County

df_subset=df.set_index('CTYNAME')[['CENSUS2010POP', 'ESTIMATESBASE1010', 'POPESTIMATE2010']]
df1 = df_subset.max(axis=1) - df_subset.min(axis=1)
print (df1)
CTYNAME
Alabama 6
Autauga County 5
Baldwin County 4
Barbour County 3
dtype: int64

print (df1.nlargest(1).reset_index(name='top1'))
CTYNAME top1
0 Alabama 6

关于python - 如何为所选列选择一行中的最大值和最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41439419/

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