我在定义每列的数据类型时,将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
5条答案
按热度按时间ttp71kqs1#
这对我很有效。
zzwlnbp82#
试试smth,像这样:
k75qkfdt3#
df =pd.read_csv('./demand. csv',dtype = dtype).dropna(how ='all')工作正常
fzsnzjdm4#
解决方案可以是:
fquxozlt5#
我不确定它是否有效,但它可以工作。这段代码在阅读csv时不加载nan值。