groupby查找具有最大值的行正在将对象转换为datetim

2024-07-01 07:19:17 发布

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

我想按两个变量['CIN','calendar']分组并返回该组的行,其中MCelig列是该特定组中最大的。可能有多行的最大值,但我只想要一行。你知道吗

例如:

  AidCode CIN  MCelig   calendar
0    None  1e       1 2014-03-08
1      01  1e       2 2014-03-08
2      01  1e       3 2014-05-08
3    None  2e       4 2014-06-08
4      01  2e       5 2014-06-08

因为前两行是一个组,所以我想要MCelig=2的行。
我想出了这句话

test=dfx.groupby(['CIN','calendar'], group_keys=False).apply(lambda x: x.ix[x.MCelig.idxmax()])

它似乎起作用了,除非我有“无”或“无”np.nan公司'对于一列的组中的所有值,该列将转换为日期时间!请参阅下面的示例,观察AidCode从一个对象到一个日期。你知道吗

import datetime as DT
import numpy as np
d = {'CIN' : pd.Series(['1e','1e','1e','2e','2e']),
'AidCode' : pd.Series([np.nan,'01','01',np.nan,'01']),
'calendar' : pd.Series([DT.datetime(2014, 3, 8), DT.datetime(2014, 3, 8),DT.datetime(2014, 5, 8),DT.datetime(2014, 6, 8),DT.datetime(2014, 6, 8)]),
'MCelig' : pd.Series([1,2,3,4,5])}
dfx=pd.DataFrame(d)
#testing whether it was just the np.nan that was the problem, it isn't
#dfx = dfx.where((pd.notnull(dfx)), None)
test=dfx.groupby(['CIN','calendar'], group_keys=False).apply(lambda x: x.ix[x.MCelig.idxmax()])

输出

Out[820]: 
                  AidCode CIN  MCelig   calendar
CIN calendar                                    
1e  2014-03-08 2015-01-01  1e       2 2014-03-08
    2014-05-08 2015-01-01  1e       3 2014-05-08
2e  2014-06-08 2015-01-01  2e       5 2014-06-08

更新:

只是想出了一个简单的解决办法

x=dfx.sort(['CIN','calendar',"MCelig"]).groupby(["CIN",'calendar'], as_index=False).last();x

既然能用,我想我选择它是为了简单。你知道吗


Tags: nonefalsedatetimeasnpdtnancalendar
1条回答
网友
1楼 · 发布于 2024-07-01 07:19:17

Pandas试图通过识别类似日期的列并将该列转换为datetime64数据类型来提供额外的帮助。这里太咄咄逼人了。你知道吗

解决方法是使用transform为每个选择最大行的组生成一个布尔掩码:

def onemax(x):
    mask = np.zeros(len(x), dtype='bool')
    idx = np.argmax(x.values)
    mask[idx] = 1
    return mask

dfx.loc[dfx.groupby(['CIN','calendar'])['MCelig'].transform(onemax).astype(bool)]

收益率

  AidCode CIN  MCelig   calendar
1      01  1e       2 2014-03-08
2      01  1e       3 2014-05-08
4      01  2e       5 2014-06-08

技术细节:当使用groupbyapply时,当单个数据帧(由应用函数返回)粘回到一个数据帧中时,Pandas会尝试猜测列 具有object dtype的是类似日期的对象,如果是,则为convert the column to an actual date dtype。如果值是字符串,它会尝试将它们解析为 使用dateutil.parser的日期:

无论好坏,dateutil.parser'01'解释为日期:

In [37]: import dateutil.parser as DP

In [38]: DP.parse('01')
Out[38]: datetime.datetime(2015, 1, 1, 0, 0)

这会导致Pandas尝试将整个AidCode列转换为日期。由于没有发生错误,它认为它只是帮助了您:)

相关问题 更多 >

    热门问题