簡體   English   中英

如何從dtype為列表的Pandas系列中刪除NaN?

[英]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 comprehensionpandas.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM