我有一个数据帧中数据帧,姑且称之为trim_df,由USER_ID索引像这样:无法子集df.apply
d_timestamp_dt flagged
user_id
1234567890 2015-04-30 False
0987654321 2015-04-30 False
我试图创建一个使用df.apply的“ACCUM”变量(),像这样:
df['new_col'] = df.apply(lambda row: my_func(row, time_period1), axis=1)
这里是my_func,并将是如何定义的?意见表明,当我运行应用()什么执行:
def my_func(row, time_period):
print type(row) # <class 'pandas.core.series.Series'>
user_id = row['user_id'] # 123456789
row_time = row['d_timestamp_dt'] # 2015-04-16 23:05:00
user_rows = trim_df.loc[user_id]
print type(user_rows) # <class 'pandas.core.series.Series'> WHY??? shouldn't it be a DataFrame?
user_rows_of_interest = user_rows[((user_rows['flagged'] == True) &
((row_time - user_rows['d_timestamp_dt']) > time_period0) &
((row_time - user_rows['d_timestamp_dt']) < time_period))]
print type(user_rows_of_interest) # <class 'pandas.tslib.Timestamp'> ...expecting this to be a DataFrame
return len(user_rows_of_interest) # breaks, because Timestamp doesn't have len()
真正令我困惑的是,当我尝试单步执行函数(不使用apply)时,我得到了我期望的DataFrame,即不是Series,然后是Timestamp。真的很感谢任何有关正在发生的事情!
time_period1 =?另外,你的函数依赖于全局的time_period0。 – Alexander
time_period1被定义为datetime.timedelta(天数= 1)。另外,我遗漏了一些非常重要的东西 - 我应用此函数的数据框df与trim_df不同,即它具有user_id列,并且由row_id而不是user_id索引。 –