我有几个可变长度列表和一些空值.一个例子是:
In [108]: s0 = pd.Series([['a', 'b'],['c'],np.nan])
In [109]: s0
Out[109]:
0 [a, b]
1 [c]
2 NaN
dtype: object
Run Code Online (Sandbox Code Playgroud)
但另一个包含所有NaNs:
In [110]: s1 = pd.Series([np.nan,np.nan])
In [111]: s1
Out[111]:
0 NaN
1 NaN
dtype: float64
Run Code Online (Sandbox Code Playgroud)
我需要每个列表中的最后一项,这很简单:
In [112]: s0.map(lambda x: x[-1] if isinstance(x,list) else x)
Out[112]:
0 b
1 c
2 NaN
dtype: object
Run Code Online (Sandbox Code Playgroud)
但是在达到这个目的的过程中,我发现,如果没有它isinstance,当它上面的索引扼流圈在以下方面NaNs 做的不s0同时s1:
In [113]: s0.map(lambda x: x[-1])
...
TypeError: 'float' object is not subscriptable
In [114]: …Run Code Online (Sandbox Code Playgroud)