panda read_csv删除空行

13z8s7eq  于 2023-04-03  发布在  其他
关注(0)|答案(5)|浏览(167)

我在定义每列的数据类型时,将CSV文件作为DataFrame阅读。如果CSV文件中有空行,则此代码会出错。如何读取没有空行的CSV?

dtype = {'material_id': object, 'location_id' : object, 'time_period_id' : int, 'demand' : int, 'sales_branch' : object, 'demand_type' : object }

df = pd.read_csv('./demand.csv', dtype = dtype)

我想到了一个解决方法,但不确定这是否是有效的方法:

df=pd.read_csv('demand.csv')
df=df.dropna()

然后重新定义df中的列数据类型。
编辑:代码-

import pandas as pd
dtype1 = {'material_id': object, 'location_id' : object, 'time_period_id' : int, 'demand' : int, 'sales_branch' : object, 'demand_type' : object }
df = pd.read_csv('./demand.csv', dtype = dtype1)
df

错误-ValueError: Integer column has NA values in column 2
我的CSV文件的快照-x1c 0d1x

ttp71kqs

ttp71kqs1#

这对我很有效。

def delete_empty_rows(file_path, new_file_path):
    data = pd.read_csv(file_path, skip_blank_lines=True)
    data.dropna(how="all", inplace=True)
    data.to_csv(new_file_path, header=True)
zzwlnbp8

zzwlnbp82#

试试smth,像这样:

data = pd.read_table(filenames,skip_blank_lines=True, a_filter=True)
k75qkfdt

k75qkfdt3#

df =pd.read_csv('./demand. csv',dtype = dtype).dropna(how ='all')工作正常

fzsnzjdm

fzsnzjdm4#

解决方案可以是:

data = pd.read_table(filenames,skip_blank_lines=True, na_filter=True)
fquxozlt

fquxozlt5#

我不确定它是否有效,但它可以工作。这段代码在阅读csv时不加载nan值。

df=pd.read_csv('demand.csv').dropna()

相关问题