微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python – 如何填充Pandas索引NaN的

我有一个Excel文件,其索引在Excel中的几行中合并,当我在pandas中加载它时,它将第一行作为索引标签读取,其余(合并的单元格)用NaN填充.如何循环索引以使其用相应的索引填充NaN?

编辑:请求删除excel的图像.我没有任何具体的代码,但我可以写一个例子.

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
...

解决方法:

试试这个:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐