【发布时间】:2021-05-15 16:52:41
【问题描述】:
我正在使用看门狗来监控一些文件夹并创建一个 csv 文件来查看文件的创建和修改时间。现在,我从 csv 中得到了这样的数据框:
full_path name created modified
0 C:\T1\1.txt 1.txt 14:04:30 NaN
1 C:\T1\1.txt 1.txt NaN 14:04:30
2 C:\T1\T2\1.txt 1.txt 14:10:30 NaN
3 C:\T1\T2\1.txt 1.txt NaN 14:10:30
4 C:\T1\T2\T3\1.txt 1.txt 14:15:30 NaN
5 C:\T1\T2\T3\1.txt 1.txt NaN 14:15:30
6 C:\T1\T2\T3\T4\1.txt 1.txt 14:20:30 NaN
7 C:\T1\T2\T3\T4\1.txt 1.txt NaN 14:20:30
8 C:\T1\2.txt 2.txt 14:25:30 NaN
9 C:\T1\2.txt 2.txt NaN 14:25:30
10 C:\T1\T2\2.txt 2.txt 14:30:30 NaN
11 C:\T1\T2\2.txt 2.txt NaN 14:30:30
12 C:\T1\T2\T3\2.txt 2.txt 14:35:30 NaN
13 C:\T1\T2\T3\2.txt 2.txt NaN 14:35:30
14 C:\T1\T2\T3\T4\2.txt 2.txt NaN 14:40:30
看门狗,通常在文件移动到另一个文件夹(创建和修改)时给出两个时间戳,但不知何故,当最后一个文件移动到 T4 文件夹时,它只给出修改后的时间戳。我使用此代码仅将此数据帧转换为两行,并将每个文件夹的时间戳放在其他列中:
m0 = (df["full_path"].ne(df["full_path"].shift(1, fill_value=df["full_path"].iloc[0])) & df["name"].eq(df["name"].shift(fill_value=df["name"].iloc[0])))
m1 = df["full_path"].eq(df.loc[df["full_path"].str.rsplit("\\", 2).str[-2] == 'T1', 'full_path'])
m2 = df["full_path"].eq(df.loc[df["full_path"].str.rsplit("\\", 2).str[-2] == 'T2', 'full_path'])
m3 = df["full_path"].eq(df.loc[df["full_path"].str.rsplit("\\", 2).str[-2] == 'T3', 'full_path'])
m4 = df["full_path"].eq(df.loc[df["full_path"].str.rsplit("\\", 2).str[-2] == 'T4', 'full_path'])
df['T1'] = np.where(m0 & m1, df['created'], "")
df['T2'] = np.where(m0 & m2, df['created'], "")
df['T3'] = np.where(m0 & m3, df['created'], "")
df['T4'] = np.where(m0 & m4, df['created'], "")
df = df.groupby(['name'], sort=False).agg({'full_path':'last','created':'first', 'modified':'last','T1':'first', 'T2':lambda x: ' '.join(set(x)), 'T3':lambda x: ' '.join(set(x)), 'T4':'last'}).reset_index()
它给了我一个像这样的数据框:
full_path name created modified T1 T2 T3 T4
0 C:\T1\T2\T3\T4\1.txt 1.txt 14:04:30 14:20:30 14:04:30 14:10:30 14:15:30 14:20:30
1 C:\T1\T2\T3\T4\2.txt 2.txt 14:25:30 14:40:30 14:25:30 14:30:30 14:35:30 NaN
如何修改我的代码以检测例如文件 2.txt 当它移动到文件夹 T4 时,如果 NaN 中的“创建”列,从“修改”列中获取时间戳,并具有类似的数据框这个:
full_path name created modified T1 T2 T3 T4
0 C:\T1\T2\T3\T4\1.txt 1.txt 14:04:30 14:20:30 14:04:30 14:10:30 14:15:30 14:20:30
1 C:\T1\T2\T3\T4\2.txt 2.txt 14:25:30 14:40:30 14:25:30 14:30:30 14:35:30 14:40:30
【问题讨论】:
标签: python python-3.x pandas dataframe python-requests