【发布时间】:2018-06-27 08:45:56
【问题描述】:
假设我有如下的时间序列数据。
df
priceA priceB
0 25.67 30.56
1 34.12 28.43
2 37.14 29.08
3 Nan 34.23
4 32 Nan
5 18.75 41.1
6 Nan 45.12
7 23 39.67
8 Nan 36.45
9 36 Nan
现在我想通过取列中先前 N 个值的平均值来填充列 priceA 中的 NaN。在这种情况下,取 N=3。 对于列 priceB,我必须用上面的 M 行值(当前索引-M)填充 Nan。
我尝试为其编写 for 循环,这不是一个好习惯,因为我的数据太大。有没有更好的方法来做到这一点?
N=3
M=2
def fillPriceA( df,indexval,n):
temp=[ ]
for i in range(n):
if i < 0:
continue
temp.append(df.loc[indexval-(i+1), 'priceA'])
return np.nanmean(np.array(temp, dtype=np.float))
def fillPriceB(df, indexval, m):
return df.loc[indexval-m, 'priceB']
for idx, rows for df.iterrows():
if idx< N:
continue
else:
if rows['priceA']==None:
rows['priceA']= fillPriceA(df, idx,N)
if rows['priceB']==None:
rows['priceB']=fillPrriceB(df,idx,M)
预期输出:
priceA priceB
0 25.67 30.56
1 34.12 28.43
2 37.14 29.08
3 32.31 34.23
4 32 29.08
5 18.75 41.1
6 27.68 45.12
7 23 39.67
8 23.14 36.45
9 36 39.67
【问题讨论】:
-
转置值矩阵以允许您对列而不是行进行操作是否可行? This answer 建议这可能是一种实用的方法,但您必须进行试验。
标签: python python-3.x pandas dataframe