我有一個如下所示的資料框,其中包含 id、進行觀察的時間戳以及檢查某個條件(和其他資訊):
id ds condYN otherinfo
1 2146-06-03 13:41:00 Y blah
1 2151-11-24 01:39:00 Y etc
2 2147-06-05 15:59:00 Y etc
3 2194-06-13 18:39:00 N etc
3 2196-09-27 18:21:00 Y etc
3 2196-10-27 12:20:00 Y etc
4 2196-11-27 11:20:00 N etc
我想過濾資料集,以便僅列出具有條件(condYN =“Y”)的人(由 id 標識),所有觀察結果直到并包括列出的條件的第一次觀察:
id ds condYN otherinfo
1 2146-06-03 13:41:00 Y blah
2 2147-06-05 15:59:00 Y etc
3 2194-06-13 18:39:00 N etc
3 2196-09-27 18:21:00 Y etc
對于每個人,我有一個元組串列,按 ID 和首次發現條件的日期戳):
[(1,2146-06-03 13:41:00),(2,2147-06-05 15:59:00),(3,2196-09-27 18:21:00)]
但我不確定如何對資料集進行這樣的過濾(匹配第一項,<= 第二項)。
uj5u.com熱心網友回復:
您可以從元組串列中創建一個pd.Series,以 id 作為索引,以日期作為值。然后map使用這個系列的原始資料框的 id 列并與 ds 列進行比較。在 a 中使用此掩碼loc來選擇所需的行。
l = [(1,'2146-06-03 13:41:00'),(2,'2147-06-05 15:59:00'),(3,'2196-09-27 18:21:00')]
s = pd.Series(map(lambda x: x[1], l), map(lambda x: x[0], l))
print(s)
# 1 2146-06-03 13:41:00
# 2 2147-06-05 15:59:00
# 3 2196-09-27 18:21:00
# dtype: object
res = df.loc[df['ds']<=df['id'].map(s)]
print(res)
# id ds condYN otherinfo
# 0 1 2146-06-03 13:41:00 Y blah
# 2 2 2147-06-05 15:59:00 Y etc
# 3 3 2194-06-13 18:39:00 N etc
# 4 3 2196-09-27 18:21:00 Y etc
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/450716.html
上一篇:檢查字串中是否有字符;如果為真則通過,如果為假則做事
下一篇:如何使用iso周制作專欄?
