中数字和字符串的最小值/最大值

2024-09-28 23:29:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个很长的数据集,希望获得一行中的最小/最大值:

    County   Year1   Year2   Year3   Year4
1   Autauga  54660   55253   51253   56253       

输出应该是

    County   Year1   Year2   Year3   Year4   Min     Max    Max-Min
1   Autauga  54660   55253   51253   56253   51253   56253  5000

我的第一个镜头产生了一个字符串作为最大值(我在论坛上读到了所有的原因):

df['Max'] = df.max(axis=1)

1)如何排除第一列,使max函数正确运行(我仍然需要输出中的县)?你知道吗

2)如何运行max、min函数并一次性计算每个值的差值?你知道吗

干杯, 第


Tags: 数据函数字符串dfmin论坛max镜头
3条回答

你可以用一点iloc切片魔法来完成这项工作。你知道吗

df['Max'] = df.iloc[:, 1:].max(axis=1)
df['Min'] = df.iloc[:, 1:].min(axis=1)
df['Max - Min'] = df['Max'] - df['Min']

df    
    County  Year1  Year2  Year3  Year4    Max    Min  Max - Min
1  Autauga  54660  55253  51253  56253  56253  51253       5000

也可以指定只对数值元素执行此操作。你知道吗

df['Max'] = df.max(axis=1, numeric_only=True)
df['Min'] = df.min(axis=1, numeric_only=True)
df['Max - Min'] = df['Max'] - df['Min']

# if you only need "Max - Min"
df['Max - Min'] = df.max(1, numeric_only=True) - df.min(1, numeric_only=True)

默认情况下,max函数将尝试使用所有内容。如果有额外的参数,它将只包括计算中包含浮点值、int值和布尔值的列。请在^{}上阅读更多信息

IIUC公司:

In [43]: df = df.assign(**{'Max-Min':df.max(1)-df.min(1)})

In [44]: df
Out[44]:
    County  Year1  Year2  Year3  Year4  Max-Min
1  Autauga  54660  55253  51253  56253     5000

相关问题 更多 >