如果我dict中是长度为2的tuple,转成df之后如何拆开他们
时间: 2024-03-01 17:49:37 浏览: 44
可以`apply`方法结合`pd.Series`将元组中的值拆分成两列:
假设原始字典为`d`,可以按照以下方式将其转换为DataFrame并拆分元组:
```python
import pandas as pd
# 假设原始字典为 d
d = {1: ('a', 10), 2: ('b', 20), 3: ('c', 30)}
# 将字典转换为DataFrame
df = pd.DataFrame.from_dict(d, orient='index')
# 使用 apply 方法结合 pd.Series 将元组拆分成两列
df[['col1', 'col2']] = df[0].apply(pd.Series)
# 删除原始列 0
df = df.drop(0, axis=1)
print(df)
```
输出:
```
col1 col2
1 a 10
2 b 20
3 c 30
```
这样,就可以将元组中的值拆分成两列,分别命名为`col1`和`col2`。
相关问题
上述代码报错:AttributeError: 'tuple' object has no attribute 'items'
抱歉,我的错误。`nx.all_pairs_dijkstra` 返回的是一个生成器对象,每个元素是一个二元组,表示一个起始节点到其他节点的最短路径和路径长度。因此,需要对生成器对象进行循环遍历,然后再对每个二元组中的第二个元素进行遍历获取每个节点和其对应的最短路径长度。以下是修改后的代码:
```python
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
df = pd.read_excel(r"C:\Users\li'yi'jie\Desktop\运筹学网络规划数据.xlsx")
edges = []
for i in range(len(df)):
edge = {
"id": df.loc[i, "边的编号"],
"tail": df.loc[i, "边的尾节点"],
"head": df.loc[i, "边的头节点"],
"length": df.loc[i, "长度"],
"capacity": df.loc[i, "容量"]
}
edges.append(edge)
plt.figure(figsize=(15,15))
G = nx.DiGraph()
for edge in edges:
G.add_edge(edge["tail"], edge["head"], weight=edge["length"])
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True)
labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
#nx.draw_networkx_edge_labels(G, pos, edge_labels=labels, label_pos=0.3)
plt.show()
all_pairs = nx.all_pairs_dijkstra(G)
rows = []
for start_node, (dist_dict, path_dict) in all_pairs:
for end_node, dist in dist_dict.items():
path_nodes = path_dict[end_node]
path_edges = []
for i in range(len(path_nodes)-1):
tail = path_nodes[i]
head = path_nodes[i+1]
for edge in edges:
if edge["tail"] == tail and edge["head"] == head:
path_edges.append(edge["id"])
break
path_edges_str = ",".join(path_edges)
rows.append({'起始节点': start_node, '终止节点': end_node, '最短路径长度': dist, '经过的边': path_edges_str})
df_result = pd.DataFrame(rows)
df_result.to_excel('all_pairs.xlsx', index=False)
```
修改后的代码中,我们使用 `nx.all_pairs_dijkstra` 函数计算所有最短路径,并且在计算过程中记录了每个最短路径经过的边的编号。然后将其一起写入Excel文件中。
阅读全文