【发布时间】: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