1 回答

TA貢獻1868條經驗 獲得超4個贊
如果缺少的值不存在,Value則使用DataFrame.insert替換值以在第一列中丟失并通過 前向填充它們,最后按和列ffill刪除行:DataFrame.dropnarename
df.insert(0, 'Location', df['Time/Location'].mask(df['Value'].notna()).ffill())
df = df.dropna(subset=['Value']).rename(columns={'Time/Location':'Time'})
print (df)
Location Time Value
1 Location1 Today 3.0
2 Location1 Next day 0.0
3 Location1 Weekend -6.0
4 Location1 Next week 1.0
6 Location2 Today 2.0
7 Location2 Next day -1.0
8 Location2 Weekend 3.0
9 Location2 Next week 2.0
11 Location3 Today 1.0
12 Location3 Next day 3.0
13 Location3 Weekend 1.0
14 Location3 Next week -1.0
16 Location4 Today 3.0
17 Location4 Next day 2.0
18 Location4 Weekend 5.0
19 Location4 Next week 4.0
21 Location5 Today 4.0
22 Location5 Next day 2.0
23 Location5 Weekend 3.0
24 Location5 Next week 1.0
26 Location6 Today -1.0
27 Location6 Next day 3.0
28 Location6 Weekend 3.0
29 Location6 Next week 2.0
另一個想法是測試第一列中的值Series.isin并過濾boolean indexing:
L = ['Today','Next day','Weekend','Next week']
m = df['Time/Location'].isin(L)
df.insert(0, 'Location', df['Time/Location'].mask(m).ffill())
df = df[m].rename(columns={'Time/Location':'Time'})
print (df)
Location Time Value
1 Location1 Today 3.0
2 Location1 Next day 0.0
3 Location1 Weekend -6.0
4 Location1 Next week 1.0
6 Location2 Today 2.0
7 Location2 Next day -1.0
8 Location2 Weekend 3.0
9 Location2 Next week 2.0
11 Location3 Today 1.0
12 Location3 Next day 3.0
13 Location3 Weekend 1.0
14 Location3 Next week -1.0
16 Location4 Today 3.0
17 Location4 Next day 2.0
18 Location4 Weekend 5.0
19 Location4 Next week 4.0
21 Location5 Today 4.0
22 Location5 Next day 2.0
23 Location5 Weekend 3.0
24 Location5 Next week 1.0
26 Location6 Today -1.0
27 Location6 Next day 3.0
28 Location6 Weekend 3.0
29 Location6 Next week 2.0
添加回答
舉報