【问题标题】:How to erase the last line from CSV file如何从 CSV 文件中删除最后一行
【发布时间】: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


【解决方案1】:

在读取 csv 文件时尝试使用 error_bad_lines 选项。希望它应该工作。

df_csv = pd.read_csv(FILENAME.csv, error_bad_lines=False)

如果你总是想忽略最后一行,试试skipfooter

df_csv = pd.read_csv(FILENAME.csv, skipfooter = 1)

文件底部要跳过的行数(engine='c' 不支持)。 Documentation

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 如果它总是最后一个元素,也许@rishi-bansai 回答一个是更好的选择,无论是在性能还是便利性方面。
    • @madhur-yadav 也是一个选项。
    【解决方案3】:

    基本上你会收到一个解析错误,因为 csv 行有一些数据丢失。

    通常,解决此问题的最佳方法是读取允许缺失值的文件。为此,您的代码应过滤缺少值的行。

    if 'X' not in line:
        # skip the line
    

    跳过一行并不是一个完美的解决方案,它是一种数据格式知识,不应该存储在代码中。您的代码不会读取任意的.csv 文件,而只会读取特定类型的文件。

    【讨论】:

      【解决方案4】:

      请阅读skipfooter - https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html#pandas.read_csv

      df_csv = pd.read_csv(FILENAME.csv, skipfooter = 1)
      

      【讨论】:

      • 嗨,我使用了skipped footer,但它也删除了rep 10,这也是我需要的东西
      • @ElizabethDC - 我正在运行代码并且工作正常,请添加 headers=None 作为参数或添加您自己的列名。也许你很困惑,因为第一个值正在成为标题。
      • 这是我输入 @MadhurYadav df4=pd.read_csv(r"U:\\user\test_node.csv",skipfooter = 1) 时得到的:ID X Y 0 rep1 1 1811 1 代表2 2 1811 2 代表3 3 1135 3 代表4 4 420 4 代表5 5 885 5 代表6 6 1010 6 代表7 7 1010 7 代表8 8 1135 8 代表9 9 1135
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多