数据帧中按最大周期分组的问题

2024-10-04 05:21:00 发布

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

我还是python的新手,在尝试对一些数据进行分组以显示具有最高(最大)日期的记录时遇到问题,数据帧如下所示:

enter image description here ... enter image description here

我正在尝试以下方法:

df_2 = df.max(axis = 0) 
df_2 = df.periodo.max()
df_2 = df.loc[df.groupby('periodo').periodo.idxmax()]

它还给了我:

Timestamp('2020-06-01 00:00:00')

periodo    2020-06-01 00:00:00
valor                  3.49136 

虽然'periodo'的值是正确的,但'valor'的值不是正确的,因为我需要获得相应的完整记录('period'和'value'),而不是每个记录的最大值。我尝试过其他方法,但我无法得到我想要的

我需要做什么

提前谢谢你,我会留意你的回答

问候


Tags: 数据方法dfvalue记录locmaxtimestamp
2条回答
# import packages we need, seed random number generator
import pandas as pd
import datetime
import random
random.seed(1)

创建示例数据帧

dates = [single_date for single_date in (start_date + datetime.timedelta(n) for n in range(day_count))]
values = [random.randint(1,1000) for _ in dates]
df = pd.DataFrame(zip(dates,values),columns=['dates','values'])

iedf将是:

    dates    values
0   2020-01-01  389
1   2020-01-02  808
2   2020-01-03  215
3   2020-01-04  97
4   2020-01-05  500
5   2020-01-06  30
6   2020-01-07  915
7   2020-01-08  856
8   2020-01-09  400
9   2020-01-10  444

选择每列中条目最高的行

你可以做:

df[df['dates'] == df['dates'].max()]

(或者,如果想使用idxmax,可以这样做:df.loc[[df['dates'].idxmax()]]

返回:

    dates   values
9   2020-01-10  444

即这是最新日期的行

&

df[df['values'] == df['values'].max()]

(或者,如果想再次使用idxmax,可以这样做:df.loc[[df['values'].idxmax()]]-就像Scott Bostonanswer。)

    dates   values
6   2020-01-07  915

即这是values中具有最高值的行

Reference

我想你需要这样的东西:

df.loc[[df['valor'].idxmax()]]

在“valor”列上使用idxmax。然后使用该索引选择该行

MVCE:

import pandas as pd
import numpy as np

np.random.seed(123)
df = pd.DataFrame({'periodo':pd.date_range('2018-07-01', periods = 600, freq='d'), 
                  'valor':np.random.random(600)+3})

df.loc[[df['valor'].idxmax()]]

输出:

       periodo     valor
474 2019-10-18  3.998918

相关问题 更多 >