[英]dataframe: forward fill next n rows on condition
我有一個看起來像這樣的 dataframe
df = pd.DataFrame({'Col1':[0,1,0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,0]})
我想要一個滾動的 function 如果出現 1 的值,接下來的 5 行將翻轉為 0。
我認為這將是一個迭代過程,但不確定如何最好地實現它。
這是使用上述規則所需的df。
df_desired = pd.DataFrame({'Col1':[0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0]})
謝謝
F
因此,要做到這一點,您需要找到 df 的所有等於 1 的索引,然后找到所有彼此連續大於 5 的索引。
df = pd.DataFrame({'Col1':[0,1,0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,0]})
ind = df[df['Col1'] == 1].index #get the indices where df == 1
#find all the indices that are consecutively greater than 5 apart
val = [ind[0]]
for k in ind[1:]:
if k - val[-1] > 5:
val.append(k)
df['Col1'] = 0 #change all the values to zero
df['Col1'][val] = 1 #change all indices where there was spaced ones to 1
這是一個簡單的解決方案:
i = 0
while i < (len(list) - 5):
if list[i] == 1:
list[i+1:i+6] = [0]*5
i += 6
i += 1
print(list)
您只需將接下來的 5 個值的切片替換為 0。 ([0]*5 創建這樣一個數組)。 然后,如果您替換,則跳過 6,否則僅跳過通常的 1。
當然,您需要先使用 pd.Series.tolist() 轉換為列表。 然后你可以添加回來
已經提供的另一種解決方案。 這只是遍歷數據框。 每次遇到 1 時,就會開始將接下來的 5 個元素翻轉為 0。
import pandas as pd
no_of_flips = 5
df = pd.DataFrame({'Col1':[0,1,0,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,0,0,0]})
df_desired = pd.DataFrame({'Col1':[0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0]})
for inx in df.index:
if i > 0:
df.at[inx, 'Col1'] = 0
i -= 1
if df.loc[inx,'Col1'] == 1:
i = no_of_flips
if (df.compare(df_desired)).empty:
print('Both dataFrames are the same!')
else:
print('Dataframes are different')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.