Python(Pandas)填充空单元格。

3

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

如果这行是空的,那么这行将被填充为前一个存在的观察值。

我的原始数据示例:

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

然而,这段代码无法正常工作。
系统提示:
TypeError: coercing to Unicode: need string or buffer, DataFrame found

如果您能帮我解决这个问题,我将不胜感激。谢谢。

2个回答

5

还有一个不太常用的ffill方法:

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

5
使用fillna()方法,可以指定方法为向前填充,如下所示。
import pandas as pd
data = pd.read_csv('sample.csv')
data = data.fillna(method='ffill') # This one forward fills all the columns.
# You can also apply to specific columns as below
# data[['bid','ask']] = data[['bid','ask']].fillna(method='ffill')
print data
    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

你确定这段代码就是我要的那个吗?看起来太简单了吧~ - Tristan Sun
试一下吧..!!! Pandas的数据操作和清洗函数非常强大且易于使用。 - Kathirmani Sukumar

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