社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python Dataframe将索引映射到一列列表以提取元素

Mainland • 3 年前 • 1372 次点击  

我有一个数据框架,由列表作为元素组成。此外,我还有一个已知索引列表。现在,我想提取每行索引中的元素。 我的代码:

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
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133629
 
1372 次点击  
文章 [ 1 ]  |  最新文章 3 年前