我有一个数据框,如下所示:
import pandas as pd
import numpy as np
s = pd.date_range('01-01-2020','01-12-2020')
df = pd.DataFrame({'folder' : ['GB123', 'GB1234']*12, 'dates' :np.repeat(s,2)})
print(df.head(5))
folder dates
0 GB123 2020-01-01
1 GB1234 2020-01-01
2 GB123 2020-01-02
3 GB1234 2020-01-02
4 GB123 2020-01-03
使用此数据框,我一直在尝试创建文件树函数,如下所示,用于显示文件和子文件夹的关系,以说明一些Blob存储体系结构。
def tree(directory):
print(f'+ {directory}')
for path in sorted(directory.rglob('*')):
depth = len(path.relative_to(directory).parts)
spacer = ' ' * depth
print(f'{spacer}+ {path.name}')
>>> tree(pathlib.Path.cwd())
+ /home/gahjelle/realpython
+ directory_1
+ file_a.md
+ directory_2
+ file_a.md
+ file_b.pdf
+ file_c.py
+ file_1.txt
+ file_2.txt
我得到的最远的结果是按文件夹分组并对其进行遍历,但是我永远无法做到正确
for folder, date in df.groupby('folder'):
print(f"-- {folder}\n\t--{date.dates}")
这给了我以下不太正确的内容。
-- GB123
--0 2020-01-01
2 2020-01-02
4 2020-01-03
6 2020-01-04
8 2020-01-05
10 2020-01-06
12 2020-01-07
14 2020-01-08
16 2020-01-09
18 2020-01-10
20 2020-01-11
22 2020-01-12
我正在追寻类似的东西:
--- GB123
--|--- 01/01/2019
|--- 02/01/2019
|--- 03/01/2019
--- GB1234
--|--- 01/01/2019
|--- 02/01/2019
|--- 03/01/2019
有人能指出我正确的方向吗?
答案 0 :(得分:1)
这与您要寻找的东西接近吗?
for f in df.folder.unique():
tdf = df[df.folder == f]
print(f"-- {f}")
for date in tdf.dates:
print(f"\t--|{date}")
输出:
-- GB123
--|2020-01-01 00:00:00
--|2020-01-02 00:00:00
--|2020-01-03 00:00:00
--|2020-01-04 00:00:00
--|2020-01-05 00:00:00
--|2020-01-06 00:00:00
--|2020-01-07 00:00:00
--|2020-01-08 00:00:00
--|2020-01-09 00:00:00
--|2020-01-10 00:00:00
--|2020-01-11 00:00:00
--|2020-01-12 00:00:00
-- GB1234
--|2020-01-01 00:00:00
--|2020-01-02 00:00:00
--|2020-01-03 00:00:00
--|2020-01-04 00:00:00
--|2020-01-05 00:00:00
--|2020-01-06 00:00:00
--|2020-01-07 00:00:00
--|2020-01-08 00:00:00
--|2020-01-09 00:00:00
--|2020-01-10 00:00:00
--|2020-01-11 00:00:00
--|2020-01-12 00:00:00