首页 > 解决方案 > 如何从 CSV 文件中删除最后一行

问题描述

我一直在使用 pandas 导入 CSV,但每次尝试使用它时都会随机收到一行额外的行,这会导致我的代码出错。如何完全擦除这条线?

我用来导入它的代码是: import itertools import copy import networkx as nx import pandas as pd import matplotlib.pyplot as plt import 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'

标签: pythonpandascsvexport-to-csv

解决方案


您可以尝试以这种方式选择列有效元素:drop[bool(drop.<column_name>[1]) == True]. 我在集合的第二个元素上使用 bool 转换,因为转换为 boolFalse的空字典是.

但是,正如 akhetos 所说,向我们展示更多您的代码以及您的源 CSV 文件会更好。


推荐阅读