【问题标题】:How to debug pandas groupby apply function如何调试熊猫 groupby 应用功能
【发布时间】:2018-08-12 13:30:35
【问题描述】:

我正在尝试理解我的前同事编写的函数。

def generate_df(group):  
    date_str = str(group['CallerLocal_Date'].iloc[-1]) + ' {0}:00:00'
    # some other functions
    return something

enrich_df = df.groupby(['LeadNumber', 'CallerLocal_Date'], as_index=False).apply(generate_df).reset_index(drop=True)

我无法完全理解上面的函数,所以我尝试分组并实际查看 date_str = str(group['CallerLocal_Date'].iloc[-1]) + ' {0}:00:00' 行的作用。

df 看起来像这样

        LeadNumber             CallerLocal_Date  Caller_TimeZone
0      7-OH4UMXXL5                   2017-09-13  America/Chicago
1      7-OL4ZHUF47                   2017-09-26  America/Chicago
2      7-OL4ZHUF47                   2017-09-26  America/Chicago
3      7-OHMFNFFC2                   2017-09-13  America/Chicago
4      7-OHMFNFFC2                   2017-09-12  America/Chicago
5      7-OGBMIPIIN                   2017-09-11  America/Chicago
6      7-OGBMIPIIN                   2017-09-07  America/Chicago
7      7-OETJOA7O6                   2017-09-01  America/Chicago
8      7-OETJOA7O6                   2017-09-06  America/Chicago
9      7-OILTU4T5O                   2017-09-18  America/Chicago
10     7-OGJHKCJFZ                   2017-09-07  America/Chicago

所以我定义了

group = df.groupby(['LeadNumber', 'CallerLocal_Date'], as_index=False)

然后打电话

date_str = str(group['CallerLocal_Date'].iloc[-1]) + ' {0}:00:00'

然后我得到了

AttributeError: Cannot access callable attribute 'iloc' of 'DataFrameGroupBy' objects, try using the 'apply' method

有人可以指出如何在不使用apply 函数的情况下调试 groupby 对象吗?

【问题讨论】:

  • 在您的 generate_df 函数print(type(group))print(group)print('\n') 中添加三个打印语句,这将让您准确查看传递的内容。

标签: pandas pandas-groupby pandas-apply


【解决方案1】:

你可以这样做:

groups = df.groupby(['LeadNumber', 'CallerLocal_Date'], as_index=False)
group = groups.get_group(list(groups.groups)[0])

然后你可以逐行运行你的代码:

date_str = str(group['CallerLocal_Date'].iloc[-1]) + ' {0}:00:00'

【讨论】:

  • 感觉pandas应该有更优雅的方式来做到这一点。可能是 df.groupby(.., debug=True, ..) 之类的参数
猜你喜欢
  • 2013-02-28
  • 2019-12-19
  • 2018-12-07
  • 1970-01-01
  • 1970-01-01
  • 2015-09-30
  • 2017-03-29
  • 1970-01-01
  • 2020-05-28
相关资源
最近更新 更多