Python 如何填写熊猫指数NaN';s
我有一个Excel文件,其中的索引在Excel中的几行上合并,当我将其加载到pandas中时,它会将第一行作为索引标签读取,其余的(合并的单元格)用NaN填充。如何循环索引,使其使用相应的索引填充NAN 编辑:根据请求删除excel的图像。我没有任何特定的代码,但我可以编写一个示例Python 如何填写熊猫指数NaN';s,python,pandas,indexing,Python,Pandas,Indexing,我有一个Excel文件,其中的索引在Excel中的几行上合并,当我将其加载到pandas中时,它会将第一行作为索引标签读取,其余的(合并的单元格)用NaN填充。如何循环索引,使其使用相应的索引填充NAN 编辑:根据请求删除excel的图像。我没有任何特定的代码,但我可以编写一个示例 import pandas as pd df = pd.read_excel('myexcelfile.xlsx', header=1) df.head() Index-he
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
请不要在此处放置图像。阅读并将一些剪贴板友好的代码放在这里。同时分享你用来阅读本文的代码。
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
df.set_index(df.index.to_series().ffill(), inplace=True)
df