1 回答

TA貢獻1887條經驗 獲得超5個贊
鑰匙
應用于每行的輸出變化可以完全由當前“級別”和前一個級別確定。這里“級別”表示具有非零條目的列的索引號。
換句話說,保留前一行級別的狀態變量足以正確填充當前行。
代碼
# the working dataset
df2 = df.iloc[:, :4].reset_index(drop=True)? # make a copy
df2.columns = range(4)? # rename columns to (0,1,2,3) for convenience
# output container
arr = np.zeros(df2.shape, dtype=int)?
# state variable: level of the last row
last_lv = 0
for idx, row in df2.iterrows():
? ? # get current indentation level
? ? lv = row.first_valid_index()
? ? if idx > 0:
? ? ? ? # case 1: same or decreased level
? ? ? ? if lv <= last_lv:
? ? ? ? ? ? # keep previous levels except current level
? ? ? ? ? ? arr[idx, :lv] = arr[idx-1, :lv]
? ? ? ? ? ? # current level++
? ? ? ? ? ? arr[idx, lv] = arr[idx-1, lv] + 1
? ? ? ? # case 2: increased level
? ? ? ? elif lv > last_lv:
? ? ? ? ? ? # keep previous levels
? ? ? ? ? ? arr[idx, :last_lv+1] = arr[idx - 1, :last_lv+1]
? ? ? ? ? ? # start counting the new levels
? ? ? ? ? ? arr[idx, last_lv+1:lv+1] = 1??
? ? # the first row
? ? else:
? ? ? ? arr[0, 0] = 1
? ? # update state variable for next use
? ? last_lv = lv
# append result to dataframe
df[["Level I", "Level II", "Level III", "Level IV"]] = arr
結果
print(df[["Level I", "Level II", "Level III", "Level IV"]])
? ? Level I? Level II? Level III? Level IV
0? ? ? ? ?1? ? ? ? ?0? ? ? ? ? 0? ? ? ? ?0
1? ? ? ? ?1? ? ? ? ?1? ? ? ? ? 0? ? ? ? ?0
2? ? ? ? ?1? ? ? ? ?1? ? ? ? ? 1? ? ? ? ?0
3? ? ? ? ?1? ? ? ? ?1? ? ? ? ? 2? ? ? ? ?0
4? ? ? ? ?1? ? ? ? ?1? ? ? ? ? 3? ? ? ? ?0
5? ? ? ? ?1? ? ? ? ?1? ? ? ? ? 3? ? ? ? ?1
6? ? ? ? ?1? ? ? ? ?1? ? ? ? ? 3? ? ? ? ?2
7? ? ? ? ?1? ? ? ? ?1? ? ? ? ? 3? ? ? ? ?3
8? ? ? ? ?1? ? ? ? ?2? ? ? ? ? 0? ? ? ? ?0
9? ? ? ? ?1? ? ? ? ?2? ? ? ? ? 1? ? ? ? ?0
10? ? ? ? 1? ? ? ? ?2? ? ? ? ? 2? ? ? ? ?0
11? ? ? ? 1? ? ? ? ?2? ? ? ? ? 3? ? ? ? ?0
12? ? ? ? 1? ? ? ? ?2? ? ? ? ? 3? ? ? ? ?1
13? ? ? ? 1? ? ? ? ?2? ? ? ? ? 3? ? ? ? ?2
14? ? ? ? 1? ? ? ? ?2? ? ? ? ? 3? ? ? ? ?3
15? ? ? ? 2? ? ? ? ?0? ? ? ? ? 0? ? ? ? ?0
16? ? ? ? 2? ? ? ? ?1? ? ? ? ? 0? ? ? ? ?0
17? ? ? ? 2? ? ? ? ?1? ? ? ? ? 1? ? ? ? ?0
筆記
該代碼只是演示了處理每一行時的邏輯是什么樣的。它尚未完全優化,因此當效率成為問題時,請考慮使用更有效的數據表示形式(例如 numpy 數組或只是級別數字列表)。
我調查了任何
tree
數據結構的庫,例如anytree和treelib,希望找到一種自動輸出樹層次結構的自動化方法。不幸的是,似乎缺乏適合讀取縮進文本文件或類似格式的 I/O 函數。這是我決定重新發明輪子的主要原因。
添加回答
舉報