gpt4 book ai didi

python - 使用 pandas 读取 csv 时设置列类型

转载 作者:太空狗 更新时间:2023-10-29 20:29:05 25 4
gpt4 key购买 nike

尝试将 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'>

enter image description here

我可以理解 pandas 可能发现很难将字典的字符串表示形式转换为给定 this 的字典和 this .但是“rating”一栏的内容怎么可能既是str又是numpy.int64???

顺便说一下,不指定引擎或 header 等调整不会改变任何内容。

感谢和问候

最佳答案

在你的循环中你正在做:

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 列的类型时所做的。

关于python - 使用 pandas 读取 csv 时设置列类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36195485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com