MYYA
如果缺少的值不存在,Value则使用DataFrame.insert替换值以在第一列中丢失并通过 前向填充它们,最后按和列ffill删除行:DataFrame.dropnarenamedf.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 Value1 Location1 Today 3.02 Location1 Next day 0.03 Location1 Weekend -6.04 Location1 Next week 1.06 Location2 Today 2.07 Location2 Next day -1.08 Location2 Weekend 3.09 Location2 Next week 2.011 Location3 Today 1.012 Location3 Next day 3.013 Location3 Weekend 1.014 Location3 Next week -1.016 Location4 Today 3.017 Location4 Next day 2.018 Location4 Weekend 5.019 Location4 Next week 4.021 Location5 Today 4.022 Location5 Next day 2.023 Location5 Weekend 3.024 Location5 Next week 1.026 Location6 Today -1.027 Location6 Next day 3.028 Location6 Weekend 3.029 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 Value1 Location1 Today 3.02 Location1 Next day 0.03 Location1 Weekend -6.04 Location1 Next week 1.06 Location2 Today 2.07 Location2 Next day -1.08 Location2 Weekend 3.09 Location2 Next week 2.011 Location3 Today 1.012 Location3 Next day 3.013 Location3 Weekend 1.014 Location3 Next week -1.016 Location4 Today 3.017 Location4 Next day 2.018 Location4 Weekend 5.019 Location4 Next week 4.021 Location5 Today 4.022 Location5 Next day 2.023 Location5 Weekend 3.024 Location5 Next week 1.026 Location6 Today -1.027 Location6 Next day 3.028 Location6 Weekend 3.029 Location6 Next week 2.0