Python(Pandas)填充空白单元格 [英] Python(Pandas) fills blanks cells

查看:320
本文介绍了Python(Pandas)填充空白单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python(Pandas)处理高频数据.基本上,我需要填写空白单元格.

I am using Python(Pandas) to manipulate high frequency data. Basically, I need to fill the blank cells.

如果此行为空白,则该行将使用先前存在的观察值进行填充.

If the this row is blank, then this row will be filled in with the previous existed observation.

我的原始数据示例:

Time    bid    ask    
15:00    .      .
15:00    .      .
15:02    76     .
15:02    .      77
15:03    .      .
15:03    78     .
15:04    .      .
15:05    .      80
15:05    .      .
15:05    .      .

需要转换为

Time    bid    ask    
15:00    .      .
15:00    .      .
15:02    76     .
15:00    76     77
15:00    76     77
15:00    78     77
15:00    78     77
15:00    78     80
15:05    78     80
15:05    78     80

这是我的代码:

#Import
tan=pd.read_csv('sample.csv')

#From here fill the blank cells

first_line = True
mydata = []
with open(tan, 'rb') as f:
    reader = csv.reader(f)
# loop through each row...
for row in reader:
    this_row = row
    # now do the blank-cell checking...
    if first_line:
        for colnos in range(len(this_row)):
            if this_row[colnos] == '':
                this_row[colnos] = 0
        first_line = False
    else:
        for colnos in range(len(this_row)):
            if this_row[colnos] == '':
                this_row[colnos] = prev_row[colnos]
    mydata.append( [this_row] )
    prev_row = this_row

但是,该代码无法正常工作.

However, the code does not work.

系统指示:

TypeError: coercing to Unicode: need string or buffer, DataFrame found

如果您能帮助我解决此问题,我非常感谢.谢谢.

I really appreciated if your can help me to solve this issue. Thanks.

推荐答案

有一种鲜为人知的 ffill 方法:

There is the lesser known ffill method:

In [102]:
df.ffill()

Out[102]:
    Time  bid  ask
0  15:00  NaN  NaN
1  15:00  NaN  NaN
2  15:02   76  NaN
3  15:02   76   77
4  15:03   76   77
5  15:03   78   77
6  15:04   78   77
7  15:05   78   80
8  15:05   78   80
9  15:05   78   80

这篇关于Python(Pandas)填充空白单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆