【发布时间】:2019-07-30 08:23:21
【问题描述】:
我一直在使用 pandas 导入 CSV,但每次我尝试使用它时都会随机收到一行额外的行,这会导致我的代码出错。如何彻底清除这条线?
我用来导入它的代码是: 导入迭代工具 导入副本 将 networkx 导入为 nx 将熊猫导入为 pd 将 matplotlib.pyplot 导入为 plt 导入csv
df3=pd.read_csv(r"U:\\user\edge_list_4.csv")
print(df3)
df4=pd.read_csv(r"U:\\user\nodes_fixed_2.csv")
df4.dropna()
print(df4)
g=nx.Graph()
for i,elrow in df3.iterrows():
g.add_edge(elrow[0], elrow[1], **elrow[2:].to_dict())
# Add node attributes
for i, nlrow in df4.iterrows():
# g.node[nlrow['id']] = nlrow[1:].to_dict() # deprecated after NX 1.11
nx.set_node_attributes(g, {nlrow['ID']: nlrow[1:].to_dict()})
# Node list example
print(nlrow)
# Preview first 5 edges
list(g.edges(data=True))[0:5]
# Preview first 10 nodes
list(g.nodes(data=True))[0:10]
print('# of edges: {}'.format(g.number_of_edges()))
print('# of nodes: {}'.format(g.number_of_nodes()))
# Define node positions data structure (dict) for plotting
for node in g.nodes(data=True):
print(node)
print("")
node_positions = {node[0]: (node[1]['X'], -node[1]['Y']) for node in
g.nodes(data=True)}
我的表是一个简单的 ID、X、Y 表。 我试过使用:
drop.na()
代码,但似乎无法将其带走。 我尝试在 Notepad++ 上对其进行编辑并将其作为 txt 文件导入,但它仍然不断出现。有什么方法我应该专门在 excel 上编辑 csv 文件还是有我可以使用的代码?
('rep1', {'X': 1, 'Y': 1811})
('rep2', {'X': 2, 'Y': 1811})
('rep3', {'X': 3, 'Y': 1135})
('rep4', {'X': 4, 'Y': 420})
('rep5', {'X': 5, 'Y': 885})
('rep6', {'X': 6, 'Y': 1010})
('rep7', {'X': 7, 'Y': 1010})
('rep8', {'X': 8, 'Y': 1135})
('rep9', {'X': 9, 'Y': 1135})
('rep10', {'X': 10, 'Y': 885})
('rep1 ', {})
该行仅适用于代表 10。
KeyError: 'X'
【问题讨论】:
-
请添加您用于导入文件的代码
标签: python pandas csv export-to-csv