好的,我有了第一个数据框 df1:
|timestamp |ip |
|2022-01-06 11:58:53+00:00|1.1.1.5. |
|2022-01-08 03:56:35+00:00|10.10.10.24|
|2022-01-09 22:29:30+00:00|3.3.3.89. |
|2022-03-08 22:37:52+00:00|8.8.8.88. |
还有第二个数据框,df2:
|timestamp |other|
|2022-01-07 22:08:59+00:00|other|
|2022-01-07 23:08:59+00:00|other|
|2022-01-09 17:04:09+00:00|other|
|2022-03-05 17:04:09+00:00|other|
我想根据 df1 中的 2 个连续时间戳计算 df2 中有多少行,意思是:
|timestamp |ip |count|
|2022-01-06 11:58:53+00:00|1.1.1.5 |NaN |
|2022-01-08 03:56:35+00:00|10.10.10.24|2 |
|2022-01-09 22:29:30+00:00|3.3.3.89 |1 |
|2022-03-08 22:37:52+00:00|8.8.8.88 |1 |
我尝试的是首先在 df1 中使用之前的时间戳创建另一个列:
df1 = df1.assign(timestamp_b4=df1.timestamp.shift(1)).fillna({'timestamp_b4': df1.timestamp})
这给了我:
|timestamp |ip |timestamp_b4 |
|2022-01-06 11:58:53+00:00|1.1.1.5 |2022-03-08 22:37:52+00:00|
|2022-01-08 03:56:35+00:00|10.10.10.24|2022-01-06 11:58:53+00:00|
|2022-01-09 22:29:30+00:00|3.3.3.89 |2022-01-08 03:56:35+00:00|
|2022-03-08 22:37:52+00:00|8.8.8.88 |2022-01-09 22:29:30+00:00|
然后做一些事情
s = (df2[df2['timestamp'].between(df1['timestamp'], df1['timestamp_b4'])].size())
但不幸的是它不起作用,因为 pandas 需要比较相同标记的对象。
有没有好的 pandas/pythonic 方法来做到这一点?
谢谢
最佳答案
def time_compare(df1,df2):
return [np.sum((df1['timestamp'].values[i-1] < df2['timestamp'].values) & (df1['timestamp'].values[i] > df2['timestamp'].values)) for i in range(len(df1.timestamp))]
df2.join(pd.Series(time_compare(df1,df2), name='Count'))
很奇怪,我无法像往常一样发布数据帧输出:
关于python - 根据另一个 df 中的列计算一个 df 中的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72462947/