如何在python eval()语句中执行“order by”?

2024-04-29 10:31:25 发布

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

在Python代码中,我有一个查询,我想从指定ID和HOUR<;=的DataFrame中选择行,但我只想选择其中的6行。所以我想订购,以避免选择太多。我搞错了。你知道吗

ID='IDTET'

t=some timestamp

HistoryThreshold=5

selection=df[df.eval("MY_ID=='%s' and HOUR<='%s' and valid=='%s' ORDER BY HOUR DESC LIMIT '%s'" %(ID,t,'yes',HistoryThreshold+1))]

我有个错误:

  MY_ID =='IDTET'and HOUR <='2019-06-18 08:00:00'and valid =='yes'ORDER BY HOUR DESC LIMIT '6'
    SyntaxError: invalid syntax

如果我只做这部分,就没有错误:

selection=df[df.eval("MY_ID=='%s' and HOUR<='%s' and valid=='%s'"%(ID,t,'yes'))]

Tags: andiddfbymyevalorderdesc
1条回答
网友
1楼 · 发布于 2024-04-29 10:31:25

你不必使用eval函数就可以做到这一点。可以在python中使用掩码。下面是它的样子:

df = pd.DataFrame({'ID' : [x for x in range(10)], 
                   'Date' : [datetime.strptime('Jun {} 2019'.format(x), '%b %d %Y') 
                             for x in range(1, 11)]})

t = datetime.strptime('Jun 09 2019', '%b %d %Y')
threshold = 5

df[df.Date < t][0:threshold]

   ID       Date
0   0 2019-06-01
1   1 2019-06-02
2   2 2019-06-03
3   3 2019-06-04
4   4 2019-06-05

如果要确保选定的行是最接近限制日期的行,可以按降序对df进行排序:

df.sort_values('Date', ascending=False, inplace = True)
df[df.Date < t][0:threshold]

   ID       Date
7   7 2019-06-08
6   6 2019-06-07
5   5 2019-06-06
4   4 2019-06-05
3   3 2019-06-04

相关问题 更多 >