使用dtype处理pandas中的缺失值来读取文件

时间:2016-12-25 20:03:02

标签: python pandas missing-data

我正在使用dtype读取一堆CSV文件,以指定每列的数据类型:

dict_tpye = {"columns_1":"int","column_2":"str"}
pd.read_csv(path,dtype=dict_tpye)

我面临的问题是,具有非浮点值的列缺少行,这会导致错误。我怎么处理这个?

我想在这种情况下使用默认值,例如数字值为0,名称为空字符串。

2 个答案:

答案 0 :(得分:1)

考虑 converter 参数,该参数使用字典,将用户定义函数的结果映射到导入列。如果字符串中的所有字符都是数字,则用户定义的方法使用返回True的内置isdigit(),如果至少有一个字符不是,则使用False;和isalpha()作为字符串对应项。根据需要进行调整,尤其是字符串,因为您可以在其内容中使用数字:

import pandas as pd

cleanFloat = lambda x: float(x if x.isdigit() else 0) 
cleanString = lambda x: str(x if x.isalpha() else '')

dict_convert = {1:cleanFloat, 2:cleanString,}
dict_type = {"columns_1":"int","column_2":"str"}

df = pd.read_csv('Input.csv', converters=dict_convert, dtype=dict_type)

答案 1 :(得分:0)

填充缺少w /占位符的一种方法是在将数据读入DataFrame后执行填充。像这样

#!/usr/bin/env python
# -*- coding: utf-8 -*- 
import numpy as np
import pandas as pd

# csv data with missing data in each of the 2 columns
csv_data = """number,colour
3,blue
12,
2,
2,red
,yellow
6,yellow
14,purple
4,green
18,green
11,orange"""

df = pd.read_csv(pd.io.parsers.StringIO(csv_data))

df.number = df.number.fillna(-999)    # fill missing numbers w/ -999
df.colour = df.colour.fillna('UNK')   # fill missing categorical w/ UNK 

print df

# In [1]: run test.py
#    number  colour
# 0     3.0    blue
# 1    12.0     UNK
# 2     2.0     UNK
# 3     2.0     red
# 4  -999.0  yellow
# 5     6.0  yellow
# 6    14.0  purple
# 7     4.0   green
# 8    18.0   green
# 9    11.0  orange