我有一个数据框架,由列表作为元素组成。此外,我还有一个已知索引列表。现在,我想提取每行索引中的元素。
我的代码:
df = pd.DataFrame({'A':[[7,8],[4,5,NaN],[NaN,1,9]],'match_idx':[1,0,NaN]})
df
A match_idx
0 [7, 8] 1
1 [4, 5, nan] 0
2 [nan, 1, 9] NaN
# in each row, let's find the values located in the match_idx position
目前的解决方案:
df['A_element'] = df.apply(lambda x: x['A'][x['match_idx']] if ~x['match_idx'].isnan() else np.nan,axis=1)
AttributeError: 'float' object has no attribute 'isnan'
预期解决方案:
df =
A match_idx A_element
0 [7, 8] 1 8
1 [4, 5, nan] 0 4
2 [nan, 1, 9] NaN NaN