【发布时间】:2014-09-05 19:42:10
【问题描述】:
当我尝试将 csv 文件导入数据框时,pandas (0.13.1) 忽略了 dtype 参数。有没有办法阻止 pandas 自行推断数据类型?
我正在合并几个 CSV 文件,有时客户包含作为字符串的字母和熊猫导入。当我尝试合并两个数据框时,我收到一个错误,因为我试图合并两种不同的类型。我需要将所有内容存储为字符串。
数据sn-p:
|WAREHOUSE|ERROR|CUSTOMER|ORDER NO|
|---------|-----|--------|--------|
|3615 | |03106 |253734 |
|3615 | |03156 |290550 |
|3615 | |03175 |262207 |
|3615 | |03175 |262207 |
|3615 | |03175 |262207 |
|3615 | |03175 |262207 |
|3615 | |03175 |262207 |
|3615 | |03175 |262207 |
|3615 | |03175 |262207 |
导入行:
df = pd.read_csv("SomeFile.csv",
header=1,
skip_footer=1,
usecols=[2, 3],
dtype={'ORDER NO': str, 'CUSTOMER': str})
df.dtypes 输出:
ORDER NO int64
CUSTOMER int64
dtype: object
【问题讨论】:
-
我正在使用 dtype 作为答案中的建议。它不能解决问题。
-
0.13.1 并不冗长,因为我认为因为
usecols而你正在回退到 python 解析器。它默默地忽略了dtype。尝试使用 0.14.0 它会 a) 工作 IIRC,b) 会在发生这种情况时发出警告(您可以尝试使用engine='c'强制引擎,此时我认为它会抱怨(即使在 0.13.1 中) -
0.13.1 即使有明确的
engine='c'也不会抱怨。我更新到 0.14.1,但它仍然无法正常工作,但你是正确的,警告为什么。ValueError: Falling back to the 'python' engine because the 'c' engine does not support skip_footer, but this causes 'dtype' to be ignored as it is not supported by the 'python' engine. (Note the 'converters' option provides similar functionality.) -
好的,是的,警告更好。另一种选择是明确地转换它,例如
df['ORDER NO'] = df['ORDER NO'].astype(object)创建后。 -
我需要保持前导 0,因为有时所有内容都作为字符串导入(例如,如果 CUSTOMER 包含 X3615)。我想我可以
df['CUSTOMER'] = df['CUSTOMER'].apply(lambda x: ('00000' + str(x))[-5:])除非有更好的方法
标签: python python-2.7 csv pandas