繁体   English   中英

Pandas - 添加列与行值应用条件相对于当前行

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM