[英]How to remove NaN from a Pandas Series where the dtype is a list?
我有一個pandas.Series
,每行的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
然后再將值提取回列表?
您可以將list comprehension
與pandas.notnull
一起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: object
帶filter
另一種解決方案,其中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
一個簡單的numpy
解決方案,列表理解:
pd.Series([np.array(e)[~np.isnan(e)] for e in x.values])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.