如何使用熊猫在两个不同的单词之间填充?

Tro*_*mba 1 python python-2.7 pandas

如果我有一个像这样的数据框:

        A
 0  Ascent
 1   NaN
 2   NaN
 3  Descent
 4   NaN
 5  Ascent
Run Code Online (Sandbox Code Playgroud)

如何填充单词之间的距离,以使“上升”和“下降”之间的nan值填充为“之上”,而使“下降”和“上升”之间的nan值填充为“下面”。这样我就得到了一个熊猫数据框,如下所示:

        A
 0  'Ascent'
 1   'Above'
 2   'Above'
 3  'Descent'
 4   'Below'
 5  'Ascent'
Run Code Online (Sandbox Code Playgroud)

cs9*_*s95 5

我决定与fillna和一起玩一点map

df

         A
0   Ascent
1      NaN
2      NaN
3  Descent
4      NaN
5   Ascent

df['A'].fillna(df['A'].ffill().map({'Ascent':'Above', 'Descent': 'Below'}))
# Identical solution, different order of method calls,
# df['A'].fillna(df['A'].map({'Ascent':'Above', 'Descent': 'Below'}).ffill())

0     Ascent
1      Above
2      Above
3    Descent
4      Below
5     Ascent
Name: A, dtype: object
Run Code Online (Sandbox Code Playgroud)