[英]How to iterate over previous rows to compare values in a Pandas DataFrame
我有一個來自 pandas 的 Dataframe ,如下所示:
import pandas as pd
raw_data = [{'Date': '1-10-19', 'Price':7, 'Check': 0},
{'Date': '2-10-19','Price':8.5, 'Check': 0},
{'Date': '3-10-19','Price':9, 'Check': 1},
{'Date': '4-10-19','Price':50, 'Check': 1},
{'Date': '5-10-19','Price':80, 'Check': 1},
{'Date': '6-10-19','Price':100, 'Check': 1}]
df = pd.DataFrame(raw_data)
df.set_index('Date')
這是它的樣子:
Price Check
Date
1-10-19 7.0 0
2-10-19 8.5 0
3-10-19 9.0 1
4-10-19 50.0 1
5-10-19 80.0 1
6-10-19 100.0 1
現在我要做的是,對於“檢查”為 1 的每一行,我想檢查價格低於該行價格 10% 的行之前的行數。例如,對於價格為 100 的第 6 行,我想遍歷前面的行並計算行,直到價格小於 10(100 的 10%),在這種情況下,價格為 9 的前 3 行。然后想將結果保存在新列中。
最終結果將如下所示:
Price Check Rows_till_small
Date
1-10-19 7.0 0 NaN
2-10-19 8.5 0 NaN
3-10-19 9.0 1 Nan
4-10-19 50.0 1 NaN
5-10-19 80.0 1 4
6-10-19 100.0 1 3
我想了很多關於如何使用某種滾動 function 來做到這一點,但我認為這是不可能的。 我還考慮過使用 iterrows 或 itertuples 遍歷整個 DataFrame,但我無法想象一種方法可以做到效率極低。
您可以通過以下方式解決問題:
import pandas as pd
raw_data = [{'Date': '1-10-19', 'Price': 7, 'Check': 0},
{'Date': '2-10-19', 'Price': 8.5, 'Check': 0},
{'Date': '3-10-19', 'Price': 9, 'Check': 1},
{'Date': '4-10-19', 'Price': 50, 'Check': 1},
{'Date': '5-10-19', 'Price': 80, 'Check': 1},
{'Date': '6-10-19', 'Price': 100, 'Check': 1}]
df = pd.DataFrame(raw_data)
new_column = [None] * len(df["Price"]) # create new column
for i in range(len(df["Price"])):
if df['Check'][i] == 1:
percent_10 = df['Price'][i] * 0.1
for j in range(i, -1, -1):
print(j)
if df['Price'][j] < percent_10:
new_column[i] = i - j
break
df["New"] = new_column # add new column
print(df)
希望回答對你有用,歡迎提問。
看一下這個
diff = df['Price'].apply(lambda x:x > (df['Price']*.1))
RTS=[]
for i in range(len(df)):
check = (diff)[i]
ind = check.idxmax()
if ind != 0:
val = (i-ind)+1
else:
val = np.nan
RTS.append(val)
df['Rows_till_small'] = RTS
print(df)
Output
Date Price Check Rows_till_small
0 1-10-19 7.0 0 NaN
1 2-10-19 8.5 0 NaN
2 3-10-19 9.0 1 NaN
3 4-10-19 50.0 1 NaN
4 5-10-19 80.0 1 4.0
5 6-10-19 100.0 1 3.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.