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
添加回答
举报
