gpt4 book ai didi

python - 遍历 CSV 以确定数据类型

转载 作者:行者123 更新时间:2023-12-02 04:21:34 25 4
gpt4 key购买 nike

所以我正在用 Python 学习入门类(class),我需要做以下事情:有一个 CSV 文件,其中有 10 列,填充了 200 行。每个都有一个 strintfloat 作为值。

示例输入:

id  gender  age marital location    income  intelliscore    emotiscore
51 F 46 M 0 15100 531 555
52 M 29 M 2 14200 673 633
53 M 25 S 0 22200 742 998
54 M 36 M 2 1000 677 646
55 F 99 S 0 10600 608 998

现在我要做的是创建另一个 CSV 文件,并用类型“替换”这些值。所以期望的结果是:

'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string'
'int', 'string', 'int', 'string', 'int', 'int', 'int', 'int', 'int'
'int', 'string', 'int', 'string', 'int', 'int', 'int', 'int', 'int'
'int', 'string', 'int', 'string', 'int', 'int', 'int', 'int', 'int'
'int', 'string', 'int', 'string', 'int', 'int', 'int', 'int', 'int'

我目前使用的代码是:

def csvfields2types(self, csvfile):
csvtypes = []
for line in csvfile:
row = []
for variable in line:
if variable == str:
row.append('string')
elif variable == float:
row.apend('float')
elif variable == int:
row.append('int')
else:
row.append('huh?')
csvtypes.append(row)
return csvtypes

它只返回一个带有“嗯?”的列表。

最佳答案

您正在检查变量的值是否为字符串。你想检查它的类型是否是一个字符串......

if type(variable) == str:

关于python - 遍历 CSV 以确定数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59431798/

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