pandas read_csv删除空白行

2024-05-23 19:13:52 发布

您现在位置:Python中文网/ 问答频道 /正文

在定义每个列的数据类型时,我以DataFrame的形式读取CSV文件。如果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文件的快照-enter image description here


Tags: 文件csv代码iddfread定义object
3条回答

试试这样的smth:

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

这对我有效。

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)

尝试.csv

s,v,h,h
1,2,3,4

4,5,6,7



9,10,1,2

Python代码

df = pd.read_csv('try.csv', delimiter=',')
print(df)

输出

   s   v  h  h.1
0  1   2  3    4
1  4   5  6    7
2  9  10  1    2

相关问题 更多 >