Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.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 在数据帧中将NaN替换为空列表_Python_Pandas_Dataframe - Fatal编程技术网

Python 在数据帧中将NaN替换为空列表

Python 在数据帧中将NaN替换为空列表,python,pandas,dataframe,Python,Pandas,Dataframe,我试图用空列表[]替换数据中的一些NaN值。但是,该列表表示为str,不允许我正确应用len()函数。在pandas中是否有用实际的空列表替换NaN值的方法 In [28]: d = pd.DataFrame({'x' : [[1,2,3], [1,2], np.NaN, np.NaN], 'y' : [1,2,3,4]}) In [29]: d Out[29]: x y 0 [1, 2, 3] 1 1 [1, 2] 2 2 NaN 3 3

我试图用空列表[]替换数据中的一些NaN值。但是,该列表表示为str,不允许我正确应用len()函数。在pandas中是否有用实际的空列表替换NaN值的方法

In [28]: d = pd.DataFrame({'x' : [[1,2,3], [1,2], np.NaN, np.NaN], 'y' : [1,2,3,4]})

In [29]: d
Out[29]:
           x  y
0  [1, 2, 3]  1
1     [1, 2]  2
2        NaN  3
3        NaN  4

In [32]: d.x.replace(np.NaN, '[]', inplace=True)

In [33]: d
Out[33]:
           x  y
0  [1, 2, 3]  1
1     [1, 2]  2
2         []  3
3         []  4

In [34]: d.x.apply(len)
Out[34]:
0    3
1    2
2    2
3    2
Name: x, dtype: int64

这使用
isnull
loc
屏蔽序列:

In [90]:
d.loc[d.isnull()] = d.loc[d.isnull()].apply(lambda x: [])
d

Out[90]:
0    [1, 2, 3]
1       [1, 2]
2           []
3           []
dtype: object

In [91]:
d.apply(len)

Out[91]:
0    3
1    2
2    0
3    0
dtype: int64
您必须使用
apply
执行此操作,以便列表对象不会被解释为要分配回df的数组,df将尝试将形状与原始序列对齐

编辑

使用更新后的示例,可以实现以下功能:

In [100]:
d.loc[d['x'].isnull(),['x']] = d.loc[d['x'].isnull(),'x'].apply(lambda x: [])
d

Out[100]:
           x  y
0  [1, 2, 3]  1
1     [1, 2]  2
2         []  3
3         []  4

In [102]:    
d['x'].apply(len)

Out[102]:
0    3
1    2
2    0
3    0
Name: x, dtype: int64

为了扩展可接受的答案,apply调用可能会特别昂贵——没有它,同样的任务也可以通过从头构建numpy数组来完成

isna = df['x'].isna()
df.loc[isna, 'x'] = pd.Series([[]] * isna.sum()).values
快速计时比较:

def empty_assign_1(s):
    s.isna().apply(lambda x: [])

def empty_assign_2(s):
    pd.Series([[]] * s.isna().sum()).values

series = pd.Series(np.random.choice([1, 2, np.nan], 1000000))

%timeit empty_assign_1(series)
>>> 172 ms ± 2.29 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit empty_assign_2(series)
>>> 19.5 ms ± 116 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

快了近10倍

您也可以使用列表理解:

d['x'] = [ [] if x is np.NaN else x for x in d['x'] ]