Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 插入空值的数据帧_Python_Pandas - Fatal编程技术网

Python 插入空值的数据帧

Python 插入空值的数据帧,python,pandas,Python,Pandas,我有两个数据帧: index a b c d 1 x x x x 2 x nan x x 3 x x x x 4 x nan x x index a b e 3 x nan x 4 x x x 5 x nan x 6

我有两个数据帧:

index  a     b      c     d
1      x     x      x     x 
2      x     nan    x     x
3      x     x      x     x
4      x     nan    x     x


index  a     b        e
3      x     nan      x 
4      x     x        x
5      x     nan      x
6      x     x        x
我想将其转换为以下内容,在这里我们只需去掉NaN值。这个问题的一个简单版本是,第二个数据帧没有nan值

index  a    b    c    d   e
1      x    x    x    x   x
2      x    x    x    x   x
3      x    x    x    x   x
4      x    x    x    x   x
5      x    x    x    x   x
6      x    x    x    x   x

使用
nan\u to\u num
将nan替换为数字:

只要应用这个:

from numpy import nan_to_num
df2 = df.apply(nan_to_num)

然后您可以根据需要合并数组。

您可以使用
combine\u first
fillna

数据帧。先合并(其他)

组合两个数据帧对象并 调用该方法的帧中的默认值为非null。结果指标 列将是各自索引和列的并集

你可以从中读取文档



所以我相信这个解决方案应该是可行的,但是对于我选择的测试数据集,我得到了一个奇怪的类型错误。对你有用吗?另外,请尝试
nan\u to_num(df)
参见上面的解决方案以获取.fillna示例。另一种方法是插值。在后来的熊猫版本中,另一个命令是。是的,fillNA是一个更好的方法。
import pandas as pd
d1 = pd.DataFrame([[nan,1,1],[2,2,2],[3,3,3]], columns=['a','b','c'])

d1
    a  b  c
0 NaN  1  1
1   2  2  2
2   3  3  3

d2 = pd.DataFrame([[1,nan,1],[nan,2,2],[3,3,nan]], columns=['b','d','e'])

d2
    b   d   e
0   1 NaN   1
1 NaN   2   2
2   3   3 NaN
d2.combine_first(d1) # d1's values are prioritized, if d2 has no NaN
    a  b  c   d   e
0 NaN  1  1 NaN   1
1   2  2  2   2   2
2   3  3  3   3 NaN

d2.combine_first(d1).fillna(5) # simply fill NaN with a value
   a  b  c  d  e
0  5  1  1  5  1
1  2  2  2  2  2
2  3  3  3  3  5