gpt4 book ai didi

python - pandas read_csv 删除空白行

转载 作者:行者123 更新时间:2023-12-04 11:33:12 30 4
gpt4 key购买 nike

我在 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 文件的快照 - enter image description here

最佳答案

这对我有用。

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)

关于python - pandas read_csv 删除空白行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52135459/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com