如何在Pandas中访问子属性?iloc切片遇KeyError问题求助
Pandas嵌套属性访问问题解决
问题原因
df.iloc[0]返回单行Series,['someprop']取出的是单个字典对象,直接用['someotherprop']能正常访问嵌套键。df.iloc[0:1]返回单行DataFrame,['someprop']得到的是元素为字典的Series,此时直接写['someotherprop']是在查找Series的索引(而非字典的键),所以触发KeyError。
正确访问方式及实现unique()的方法
方法1:用apply提取嵌套值
对存储字典的Series逐个提取目标键:
df['someprop'].apply(lambda x: x['someotherprop']).unique()
方法2:用str.get()简化操作
Pandas Series的str.get()方法专门用于提取字典元素,写法更简洁:
df['someprop'].str.get('someotherprop').unique()
针对切片DataFrame的访问
如果需要处理df.iloc[0:1]这类切片结果,同样适用上述方法:
df.iloc[0:1]['someprop'].str.get('someotherprop')
内容的提问来源于stack exchange,提问作者Jenia Be Nice Please
相关产品推荐
相关产品推荐

