Pandas 带日期时间的数据框列表迭代

Pandas dataframe list iteration with datetime

我有一个每 15 分钟运行一次的作业和 returns 一个像这样的 IP 数组列表

listofIPs = ['1.1.1.1', '2.2.2.2', '3.3.3.3']

我将其保存在一个 masterlist.csv 文件中,日期如下。

IP,Timestamp
1.1.1.1,2022-05-12_2030
2.2.2.2,2022-05-12_2030
3.3.3.3,2022-05-12_2030
5.5.5.5,2022-05-12_1430
8.8.8.8,2022-05-11_1930
1.1.1.1,2022-05-06_2030

每 15 分钟作业 returns 某些 IP list.We 需要检查列表中的任何 IP 在过去 24 小时内是否不存在于主 csv 中,然后仅追加该 IP 主控 csv 文件

我想使用 Pandas 数据帧或基本 python 而不是 Pyspark 等

我试过类似的方法,但没有用

   mainfile = '/Users/Documents/masterlist.csv'
   runtime = datetime.strftime(now , '%Y-%m-%d_%H%M')
   listofIPs = ['1.1.1.1', '2.2.2.2', '3.3.3.3']
  
   dateparse = lambda x: datetime.strptime(x, '%Y-%m-%d_%H%M')
   df = pd.read_csv(mainfile, parse_dates=['Timestamp'], date_parser=dateparse)
   recent_df = df[df.timestamp > datetime.now() - pd.to_timedelta("1day")]
   badip_df = recent_df.drop_duplicates("IP", keep='last')
   
   if badip_df.empty:
        badip_df['Timestamp'] = runtime
        badip_df = badip_df[[listofIPs, 'Timestamp']]
        badip_df.to_csv(mainfile, index=False)
    else:
        badip_df.to_csv(mainfile, mode='a', index=False, header=False)
    

有人可以帮忙吗?

datetime.strftimedatetime.strptimedatetime.now() 不存在。所有这些都是 datetime.datetime 的方法,例如datetime.datetime.now() [编辑:哦,除非您使用 from datetime import datetime] 导入。

另外,如评论中所述,goodfp_df在首次使用之前未定义。解决这些问题,你就会有所作为。它应该被定义为 recent_df[~recentdf.duplicated(keep=False)] 吗?

此外,df.timestamp 应该是 df.Timestamp,并且 now 没有定义(应该是 datetime.now())。

最后,listofIPs 是一个列表,因此不能是数据框的列标题。

这应该是请求的解决方案。它仅将新 IP 附加到 CSV 文件(例如,我将 1.1.1.1 更改为 1.1.1x):

import pandas as pd
from datetime import datetime

mainfile = 'masterlist.csv'
runtime = datetime.strftime(datetime.now(), '%Y-%m-%d_%H%M')
listofIPs = ['1.1.1.x', '2.2.2.2', '3.3.3.3']

dateparse = lambda x: datetime.strptime(x, '%Y-%m-%d_%H%M')
df = pd.read_csv(mainfile, parse_dates=['Timestamp'], 
date_parser=dateparse)
recent_df = df[df.Timestamp > datetime.now() - pd.to_timedelta("100 days")]
unique_ip_df = recent_df.drop_duplicates("IP", keep='last')

unique_ip_df.Timestamp = unique_ip_df.Timestamp.apply(lambda x: 
datetime.strftime(x, '%Y-%m-%d_%H%M'))
complete_df = unique_ip_df.append([{'IP': IP, 'Timestamp': runtime} for IP in listofIPs if not IP in unique_ip_df.IP.values])
complete_df.to_csv(mainfile, mode='w', index=False, header=True)