python-熊猫:从分层数据创建字典
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python-熊猫:从分层数据创建字典,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1560字,纯文字阅读大概需要3分钟。
内容图文
![python-熊猫:从分层数据创建字典](/upload/InfoBanner/zyjiaocheng/669/cfc2effafe134c3e88abc03442492828.jpg)
说我有以下数据框df:
A B
0 mother1 NaN
1 NaN child1
2 NaN child2
3 mother2 NaN
4 NaN child1
5 mother3 NaN
6 NaN child1
7 NaN child2
8 NaN child3
你怎么能把它变成字典,产生:
结果= {‘mother1’:[‘child1′,’child2’],’mother2’:[‘child1’],’mother3’:[‘child1′,’child2′,’child3’]}
我对此:
import pandas as pd
import numpy as np
results={}
for index1,row1 in df.iterrows():
if row1['A'] is not np.nan:
children=[]
for index2,row2 in df.iterrows():
if row2['B'] is not np.nan:
children.append(row2['B'])
results[row1['A']]=children
但是,结果是错误的:
In[1]: results
Out[1]:
{'mother1': ['child1', 'child2', 'child1', 'child1', 'child2', 'child3'],
'mother2': ['child1', 'child2', 'child1', 'child1', 'child2', 'child3'],
'mother3': ['child1', 'child2', 'child1', 'child1', 'child2', 'child3']}
解决方法:
这是一种方法:
df['A'].fillna(method='ffill', inplace=True)
给予:
A B
0 mother1 NaN
1 mother1 child1
2 mother1 child2
3 mother2 NaN
4 mother2 child1
5 mother3 NaN
6 mother3 child1
7 mother3 child2
8 mother3 child3
然后删除子NA:
df.dropna(subset=['B'], inplace=True)
给予:
A B
1 mother1 child1
2 mother1 child2
4 mother2 child1
6 mother3 child1
7 mother3 child2
8 mother3 child3
然后,您可以使用groupby和字典理解功能来获得最终结果:
results = {k: v['B'].tolist() for k, v in df.groupby('A')}
结果:
{'mother1': ['child1', 'child2'],
'mother2': ['child1'],
'mother3': ['child1', 'child2', 'child3']}
内容总结
以上是互联网集市为您收集整理的python-熊猫:从分层数据创建字典全部内容,希望文章能够帮你解决python-熊猫:从分层数据创建字典所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。