[英]pandas read_csv remove blank rows
我在定義每列的數據類型時將 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
這對我有用。
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)
像這樣嘗試:
data = pd.read_table(filenames,skip_blank_lines=True, a_filter=True)
解決方案可能是:
data = pd.read_table(filenames,skip_blank_lines=True, na_filter=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
我不確定它是否有效,但它有效。 此代碼在讀取 csv 時不會加載 nan 值。
df=pd.read_csv('demand.csv').dropna()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.