如何填充Pandas索引中的NaN值

3
我有一个Excel文件,其中的索引跨越了几行并在Excel中合并。当我在pandas中加载它时,它将第一行读作索引标签,而其余部分(合并单元格)则填充为NaN。如何循环遍历索引以便使用相应的索引填充NaN?
import pandas as pd
df = pd.read_excel('myexcelfile.xlsx', header=1)
df.head()
                     Index-header               Month
0                          Index1                   1   
1                           NaN                     2    
2                           NaN                     3    
3                           NaN                     4     
4                           NaN                     5
5                           Index2                  1
6                           NaN                     2
...

1
请不要在此处放置图片。请阅读如何创建可重现的Pandas示例,并在此处放置一些剪贴板友好的代码。同时分享您用于读取此内容的代码。 - Ivan
2个回答

4

试试这个:

In [205]: df
Out[205]:
    Index-header  Month
0         Index1    1.0
1            NaN    2.0
2            NaN    3.0
3            NaN    4.0
4            NaN    5.0
5         Index2    1.0
6            NaN    2.0
...          NaN    NaN

In [206]: df['Index-header'] = df['Index-header'].fillna(method='pad')

In [207]: df
Out[207]:
    Index-header  Month
0         Index1    1.0
1         Index1    2.0
2         Index1    3.0
3         Index1    4.0
4         Index1    5.0
5         Index2    1.0
6         Index2    2.0
...       Index2    NaN

2
from StringIO import StringIO
import pandas as pd

txt = """Index1,1
,2
,3
Index2,1
,2
,3"""

df = pd.read_csv(StringIO(txt), header=None, index_col=0, names=['Month'])
df

enter image description here

df.set_index(df.index.to_series().ffill(), inplace=True)
df

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接