根据'编码'应用浮点值。带循环的整数

时间:2018-01-04 21:48:18

标签: python pandas

我有一个整数数据帧,我想根据整数值映射浮点值。浮点列表示应映射到的整数值。对于浮点数据帧中的每个时间步,应该创建一个新的数据帧。我希望的最终产品实际上是一个浮点栅格。

整数的数据框可以是:

df = pd.DataFrame(np.random.randint(0,4,size=(5,5)))
print(df)
   0  1  2  3  4
0  1  3  2  3  0
1  3  3  0  1  3
2  1  1  0  2  3
3  3  0  3  0  3
4  1  1  3  0  1

浮点值可以是:

df2 = pd.DataFrame(np.random.random(25).reshape(5,5),
                   index=pd.date_range(start='2012-1-1',end='2012-6-1',freq='M'))
print(df2)
                   0         1         2         3         4
2012-01-31  0.892510  0.186048  0.960318  0.415110  0.930342
2012-02-29  0.944020  0.497700  0.735165  0.106957  0.640663
2012-03-31  0.135279  0.472433  0.761687  0.565476  0.482689
2012-04-30  0.630033  0.719444  0.078893  0.070138  0.392354
2012-05-31  0.686622  0.823896  0.551767  0.898720  0.569068

到目前为止,通过明确地执行代码和时间步骤,我已经能够通过mask做得不好看。

# Crop code is the column in df2(float) and value in df(int) 
cropcode = 1
# 2012-01-31
ts = 0
df.mask( df == cropcode, df2[cropcode][ts],inplace=True)

print(df)
          0         1  2         3         4
0  0.186048  3.000000  2  3.000000  0.000000
1  3.000000  3.000000  0  0.186048  3.000000
2  0.186048  0.186048  0  2.000000  3.000000
3  3.000000  0.000000  3  0.000000  3.000000
4  0.186048  0.186048  3  0.000000  0.186048

...依此类推,直到所有值都被替换。在这个例子中,将有5个产生的浮点栅格,每个月一个。我似乎无法为我实现这个目标。

1 个答案:

答案 0 :(得分:0)

有一种方法

df2.columns=df.columns.astype(int)
df.replace(df2.T.iloc[:,0].to_dict())
Out[15]: 
          0         1         2         3         4
0  0.186048  0.415110  0.960318  0.415110  0.892510
1  0.415110  0.415110  0.892510  0.186048  0.415110
2  0.186048  0.186048  0.892510  0.960318  0.415110
3  0.415110  0.892510  0.415110  0.892510  0.415110
4  0.186048  0.186048  0.415110  0.892510  0.186048

使用for循环

l = []
for i in df2.columns:
    l.append(df.replace(df2.T.iloc[:,i].to_dict()))