我有一个pandas.Series,其中每一行的数据类型都是一个列表对象。例如。
>>> import numpy as np
>>> import pandas as pd
>>> x = pd.Series([[1,2,3], [2,np.nan], [3,4,5,np.nan], [np.nan]])
>>> x
0 [1, 2, 3]
1 [2, nan]
2 [3, 4, 5, nan]
3 [nan]
dtype: object如何删除每行列表中的nan?
期望的输出将是:
>>> x
0 [1, 2, 3]
1 [2]
2 [3, 4, 5]
3 []
dtype: object这是可行的:
>>> x.apply(lambda y: pd.Series(y).dropna().values.tolist())
0 [1, 2, 3]
1 [2.0]
2 [3.0, 4.0, 5.0]
3 []
dtype: object有没有比使用lambda更简单的方法,将列表转换为Series,删除NaN,然后将值重新提取到列表中?
发布于 2017-01-04 14:26:16
您可以结合使用list comprehension和pandas.notnull来删除NaN值:
print (x.apply(lambda y: [a for a in y if pd.notnull(a)]))
0 [1, 2, 3]
1 [2]
2 [3, 4, 5]
3 []
dtype: objectfilter的另一种解决方案,条件是v!=v仅适用于NaN
print (x.apply(lambda a: list(filter(lambda v: v==v, a))))
0 [1, 2, 3]
1 [2]
2 [3, 4, 5]
3 []
dtype: object感谢DYZ提供的另一种解决方案:
print (x.apply(lambda y: list(filter(np.isfinite, y))))
0 [1, 2, 3]
1 [2]
2 [3, 4, 5]
3 []
dtype: object发布于 2017-01-04 14:31:45
一个支持列表理解的简单numpy解决方案:
pd.Series([np.array(e)[~np.isnan(e)] for e in x.values])https://stackoverflow.com/questions/41457408
复制相似问题