![](/img/trans.png)
[英]How to insert row into pandas dataframe if a condition is not met?
[英]Insert row in Pandas Dataframe based on a condition
我正在使用Pandas來處理龐大的時間序列數據集。 如果兩個連續索引之間的差異大於5,我想在數據框中的行之間添加行。
實際:
a result
Date
1497544649 1 1.0
1497544652 9 1.0
1497544661 9 NaN
預期:
a result
Date
1497544649 1 1.0
1497544652 9 1.0
1497544657 9 0
1497544661 9 NaN
我在索引上使用diff()來獲取兩個連續索引之間的差異,但是如果差異大於5則不確定如何插入記錄。
import pandas as pd
df = pd.DataFrame([{"Date": 1497544649,"a":1, "result": 1},
{"Date": 1497544652,"a": 9, "result": 1},
{"Date": 1497544661,"a": 9, "result": 1}])
df.set_index("Date", inplace=True)
df.index.to_series().diff().fillna(0).to_frame("diff")
任何關於如何實現這一點的指示將不勝感激
謝謝
你有一個良好的開端。 添加diff列以便於過濾。
獲取與您的規則匹配的數據框的索引並插入您的行。
df['diff'] = df.index.to_series().diff().fillna(0).to_frame("diff")
matches = df[df['diff'] > 5].index.tolist()
for i in matches:
diff = df.loc[i]['diff']
interval = round(diff/2) # index some place in the middle
df.loc[i-interval] = [0, 0, 0, diff-interval] # insert row before matched index
df.loc[i]['diff'] = interval # may not need to update the interval
df.sort_index(inplace=False) # pandas appends by default so we should sort this
del df.diff # we can remove this
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.