在数据框

时间:2017-11-28 12:13:42

标签: python pandas numpy dataframe concatenation

我有以下数据框:

import numpy as np
import pandas as pd

df1 = pd.DataFrame(np.random.randint(1, size=(5,5)))
df2 = pd.DataFrame(np.random.randint(10, size=(2,2)))

当我这样做时,我没有问题:

df1.iloc[0:2,0:2] = df2

结果:

6  4  0  0  0
9  2  0  0  0
0  0  0  0  0
0  0  0  0  0

但是当我尝试这个时:

df1.iloc[0:2,3:5] = df2

结果如下:

0.0  0.0  0.0  NaN  NaN
0.0  0.0  0.0  NaN  NaN
0.0  0.0  0.0  0.0  0.0
0.0  0.0  0.0  0.0  0.0
0.0  0.0  0.0  0.0  0.0

如何将此NaN转换为df2?

1 个答案:

答案 0 :(得分:1)

可能设置为numpy array,但必须与df2相同的形状iloc进行选择:

print (df1.iloc[0:2,0:2].shape)
(2, 2)
print (df2.shape)
(2, 2)

df1.iloc[0:2,3:5] = df2.values
print (df1)
   0  1  2  3  4
0  0  0  0  8  5
1  0  0  0  0  4
2  0  0  0  0  0
3  0  0  0  0  0
4  0  0  0  0  0