我試圖尋找從第 2 行開始的“this”大于“that”的真實條件(索引大于 1)。例如,如果 df 有 5 行長,并且在第 1、4 和 5 行中“this”大于“that”,則回傳值為 0,0,0,1,1。索引本身是一個日期時間字串。但是, someinteger 是實際的索引行值(df 的從零到長度為 1 的值)它看起來很容易和微不足道,但我遇到了困難。我已經嘗試過了,但它不起作用。
import panda as pd
import numpy as np
df = pd.DataFrame({
'this': [5,2,2,5,5],
'that': [3,3,3,3,3]},
index=['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04', '2022-01-05'])
df.index = pd.to_datetime(df.index)
someintegervalue = 1
df['blah blah blah'] = np.where(df.index > someintegervalue & df['this'] > df['that'], 0, 1)
uj5u.com熱心網友回復:
IIUC,你可以這樣做:
import numpy as np
df['blah blah blah']= np.where(np.arange(len(df)) > someintegervalue & df['this']>df['that'], 0, 1)
uj5u.com熱心網友回復:
你很親密。您只需將條件括在 () 中并翻轉最后兩個 np.where() 引數。
import pandas as pd
import numpy as np
df = pd.DataFrame({
'this': [5,2,2,5,5],
'that': [3,3,3,3,3]},
index=['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04', '2022-01-05'])
df.index = pd.to_datetime(df.index)
df['blah blah blah']= np.where((df.index > df.index[1]) & (df['this'] > df['that']), 1, 0)
或者,如果您想輸入日期而不是索引位置,則可以使用它。
from pandas import Timestamp
df['blah blah blah']= np.where((df.index > Timestamp('2022-01-02')) & (df['this'] > df['that']), 1, 0)
輸出:
this that blah blah blah
2022-01-01 5 3 0
2022-01-02 2 3 0
2022-01-03 2 3 0
2022-01-04 5 3 1
2022-01-05 5 3 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/433833.html
