如何将NULL当作使用pandas的普通字符串? [英] How to treat NULL as a normal string with pandas?

查看:43
本文介绍了如何将NULL当作使用pandas的普通字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有字符串列的csv文件,我想用熊猫阅读它.在此文件中,字符串null作为实际值出现,不应视为缺失值.

I have a csv-file with a column with strings and I want to read it with pandas. In this file the string null occurs as an actual value and should not be regarded as a missing value.

示例:

import pandas as pd
from io import StringIO

data = u'strings,numbers\nfoo,1\nbar,2\nnull,3'
print(pd.read_csv(StringIO(data)))

这将提供以下输出:

  strings  numbers
0     foo        1
1     bar        2
2     NaN        3

我该怎么做才能将值null本身(而不是NaN)获取到DataFrame中?可以假定该文件不包含任何实际缺少的值.

What can I do to get the value null as it is (and not as NaN) into the DataFrame? The file can be assumed to not contain any actually missing values.

推荐答案

您可以为string列指定converters自变量.

You can specify a converters argument for the string column.

pd.read_csv(StringIO(data), converters={'strings' : str})

  strings  numbers
0     foo        1
1     bar        2
2    null        3

这将绕过熊猫的自动解析.

This will by-pass pandas' automatic parsing.

另一个选项是设置na_filter=False:

pd.read_csv(StringIO(data), na_filter=False)

  strings  numbers
0     foo        1
1     bar        2
2    null        3

这适用于整个DataFrame,因此请谨慎使用.如果您要通过外科手术将其应用于选择列,则建议使用第一种选择.

This works for the entire DataFrame, so use with caution. I recommend first option if you want to surgically apply this to select columns instead.

这篇关于如何将NULL当作使用pandas的普通字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆