[英]Pandas DataFrame, calculate max column value relative to current row column value
[英]Pandas - add column with row value applying conditions relative to current row
我正在嘗試向我的 dataframe 添加一個新列,其中包含第一個實例的時間值,其中刻度等於當前刻度加 1。
df2 是這樣的:
Time Tick Desired col
Count
0 1594994400 3212.25 1594994405
1 1594994401 3212.00 1594994404
2 1594994402 3212.25 1594994405
3 1594994402 3212.50 NaN
4 1594994403 3212.75 NaN
5 1594994404 3212.75 NaN
6 1594994404 3213.00 NaN
7 1594994405 3213.25 NaN
8 1594994405 3213.25 NaN
9 1594994405 3213.25 NaN
我希望做類似的事情:
df2['Desired col'] = df2['Tick'].loc[(df2['Tick'(other rows)]==df2['Tick'current row] +1)&(df2['Time'(other rows)]>=df2['Time'](current row)].idxmax()
希望這是有道理的。 我是 pandas 和 python 的新手,這是我發布的第一個問題。 非常感謝 stackoverflow 社區提供的所有優秀參考資料!
如果你想要一個襯里,應該這樣做:
df['Desired'] = df.apply(lambda x: df[df['Tick'] == x['Tick']+1].reset_index().iloc[0]['Timestamp'], axis=1)
問題是它會拋出一個 KeyError [0] 因為在你的'Tick'列中你並不總是有tick + 1,我建議是這樣的:
def desired_generator(row, df):
try:
return df[df['Tick'] == row['Tick']+1].reset_index().iloc[0]['Timestamp']
except:
return None
df['Desired'] = df.apply(lambda x: desired_generator(x, df), axis=1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.