【发布时间】:2015-09-10 07:54:41
【问题描述】:
我有一个数据框,我一次循环遍历一天,并根据特定标准确定当天的哪些项目符合条件。然后我需要标记那些符合条件的项目。数据框:
date abc xyz rth
index
apple 2015-01-27 23 5712 713
2015-01-28 234 1357 9541
2015-01-29 489 185 278
2015-01-30 154 951 754
pear 2015-01-27 4786 7531 4751
2015-01-28 476 367 45
2015-01-29 15 37 783
2015-01-30 489 185 421
grape 2015-01-27 2513 57 513
2015-01-28 237 587 733
2015-01-29 7869 472 759
2015-01-30 489 185 278
例如,我需要为每个日期标记满足以下条件的每个项目:
- abc > 50
- xyz > 700
- rth = 一旦我有一个基于上述标准的候选名单,从这个候选名单中选择具有 rth 最大值的单个项目
上述条件的输出将是:
date abc xyz rth meets_criteria
index
apple 2015-01-27 23 5712 713
2015-01-28 234 1357 9541 True
2015-01-29 489 185 278
2015-01-30 154 951 754 True
pear 2015-01-27 4786 7531 4751 True
2015-01-28 476 367 45
2015-01-29 15 37 783
2015-01-30 489 185 421
grape 2015-01-27 2513 57 513
2015-01-28 237 587 733
2015-01-29 7869 472 759
2015-01-30 489 185 278
如您所见,每天 27 日、28 日、30 日有一件商品符合条件。 29日没有项目符合条件。
到目前为止,为了能够每天进行评估,我已经完成了以下工作:
unique_dates = df['date'].unique()
for i in range(0, len(unique_dates)):
today_df = df.loc[df['date'] == unique_dates[i]]
today_df = today_df.loc[today_df['abc'] > 50]
today_df = today_df.loc[today_df['xyz'] > 700]
today_df = today_df.sort('rth')
today_df = today_df.tail(1)
这给了我每天的合格项目(如果有的话)。我的问题是我不知道如何从 today_df 中获取符合条件的项目并将其标记在原始数据框中的正确行上。
【问题讨论】:
-
df.loc[(df['abc']> 50) & (df['xyz']> 700), 'rth'].max(level='date')做你想做的事吗? -
谢谢,但是我收到错误:ValueError:级别名称日期不是索引的名称。此外,这些标准只是一个示例。可能存在我需要最大 X 行来表示“rth”的情况。不仅仅是单一的最大值。即:在我的示例中,最后一行可能是 today_df = today_df.tail(2) 例如。