首页 > 解决方案 > 日期格式以及如何打印出现的最大数字和日期

问题描述

在以下数据中,我想获得发生的最多次数以及Swings发生在什么上Date。我已经可以获得发生的最大摇摆次数,但不确定如何获得相应的日期:

data = [
    {"Date": "01/06/2020",  "Swings": 350},
    {"Date": "02/06/2020",  "Swings": 370},
]
df = pd.DataFrame(data)

max_swings = max(df['Swings'])

print ("The max number of swings in one day was: " + str(max_swings))

(注:我使用 DD/MM/YYYY 日期格式)

标签: pythonpandas

解决方案


通常我们将日期转换为datetime.

df['Date'] = pd.to_datetime(df['Date']) # convert to datetime

df.iloc[df['Swings'].idxmax()] # this gives you the row with the highest swings

df['Swings'].idxmax()为您提供 Swings 最大值所在的第一次出现的索引。然后您可以使用.iloc[]


推荐阅读