[英]How to convert pandas DataFrame to dictionary for Newick format
我有以下数据集:
import pandas as pd
df = pd.DataFrame([['root', 'b', 'a', 'leaf1'],
['root', 'b', 'a', 'leaf2'],
['root', 'b', 'leaf3', ''],
['root', 'b', 'leaf4', ''],
['root', 'c', 'leaf5', ''],
['root', 'c', 'leaf6', '']],
columns=['col1', 'col2', 'col3', 'col4'])
因为没找到直接转成Newic格式的方法,所以想转成字典,格式如下:
node_to_children = {
'root': {'b': 0, 'c': 0},
'a': {'leaf1': 0, 'leaf2': 0},
'b': {'a': 0, 'leaf3': 0, 'leaf4': 0},
'c': {'leaf5': 0, 'leaf6': 0}
}
然后我最终可以将此 node_to_children 转换为 Newic 格式,但是,如何将 pandas DataFrame 转换为字典?
我假设您的 dataframe 中的每一行都代表树从根到叶的一个完整分支。 基于此,我想出了以下解决方案。 可以在下面的代码中找到对算法中每个步骤的注释,但如果有任何不清楚的地方,请随时询问。
node_to_children = {}
#iterate over dataframe row-wise. Assuming that every row stands for one complete branch of the tree
for row in df.itertuples():
#remove index at position 0 and elements that contain no child ("")
row_list = [element for element in row[1:] if element != ""]
for i in range(len(row_list)-1):
if row_list[i] in node_to_children.keys():
#parent entry already existing
if row_list[i+1] in node_to_children[row_list[i]].keys():
#entry itself already existing --> next
continue
else:
#entry not existing --> update dict and add the connection
node_to_children[row_list[i]].update({row_list[i+1]:0})
else:
#add the branching point
node_to_children[row_list[i]] = {row_list[i+1]:0}
Output:
print(node_to_children)
{'root': {'b': 0, 'c': 0},
'b': {'a': 0, 'leaf3': 0, 'leaf4': 0},
'a': {'leaf1': 0, 'leaf2': 0},
'c': {'leaf5': 0, 'leaf6': 0}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.