尝试使用以下格式将csv文件读入pandas数据框
dp = pd.read_csv('products.csv', header = 0, dtype = {'name': str,'review': str,
'rating': int,'word_count': dict}, engine = 'c')
print dp.shape
for col in dp.columns:
print 'column', col,':', type(col[0])
print type(dp['rating'][0])
dp.head(3)
这是输出:
(183531, 4)
column name : <type 'str'>
column review : <type 'str'>
column rating : <type 'str'>
column word_count : <type 'str'>
<type 'numpy.int64'>
我可以理解,大熊猫可能会发现很难在给定this和this的情况下将字典的字符串表示形式转换成字典。但是如何将“ rating”列的内容同时设置为str和numpy.int64?
顺便说一句,未指定引擎或标头之类的调整不会更改任何内容。
谢谢并恭祝安康
在循环中,您正在执行以下操作:
for col in dp.columns:
print 'column', col,':', type(col[0])
并且您正确地看到str
了随处可见的输出,因为col[0]
它是列名称的首字母,即字符串。
例如,如果运行此循环:
for col in dp.columns:
print 'column', col,':', col[0]
您将看到每个列名称的字符串的第一个字母被打印出来-这就是事实col[0]
。
您的循环仅循环访问列名,而不循环访问序列数据。
您真正想要的是在循环中检查每一列数据的类型(而不是其标题或标题的一部分)。
因此,请改为执行此操作以获取列数据(非标题数据)的类型:
for col in dp.columns:
print 'column', col,':', type(dp[col][0])
这类似于您分别打印rating
列的类型时所做的操作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句