繁体   English   中英

如何使用python将csv文件中的None行删除?

[英]How do I drop the None line in a csv file using python?

例如,我有以下csv数据集:

[1,2,3,4]
[3,5,2,5]
[,3,2,4]

如您在上面的数据集中看到的,存在一个列表,其中包含无值。

在上述情况下,我想删除csv中具有None值的列表。

当我尝试时,我什至无法尝试擦除它,因为我无法读取空值。

请提出一种擦除方法。

这是我的尝试。

-在将xlsx数据放入名为data的变量之前。

while k < cols:
    if data[i] != None:
        with open('data.csv', 'a') as f:
        writer = csv.writer(f)
        writer.writerows(data)
        f.close()

为了删除具有“空”单元格的行,请执行以下操作:

1.将.csv导入pandas数据框

import pandas as pd

df_csv = pd.read_csv('yourfile.csv')

2.删除NaN行

df_csv.dropna(axis = 0, how = 'any', inplace = True) 
# axis = 1 will drop the column instead of the row
# how = 'all' will only drop if all cells are NaN

3.保存到.csv

df_csv.to_csv('yourfile_parsed.csv', index = False)

评论

  1. 最好是指NoneNaN而不是说出' empty '
  2. 另外,“ clear ”(最好称为“ drop ”)-人们可能会认为您想删除所有值,同时保留行

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM