Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 迭代CSV以确定数据类型_Python_Loops_File_Csv - Fatal编程技术网

Python 迭代CSV以确定数据类型

Python 迭代CSV以确定数据类型,python,loops,file,csv,Python,Loops,File,Csv,因此,我正在用Python学习初学者课程,我需要做以下几点:有一个CSV文件,其中有10列,填充了200行。每个都有一个str、int或float作为值 输入示例: 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 2220

因此,我正在用Python学习初学者课程,我需要做以下几点:有一个CSV文件,其中有10列,填充了200行。每个都有一个
str
int
float
作为值

输入示例:

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

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

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

if type(variable) == str:

您熟悉Python中的EAFP原则吗?如果没有,请查看此问题:

我们可以在这里做类似的事情:您可以使用
try
来“测试”类型,只需假设字符串表示该类型的值并将其转换即可。如果有效,我们找到了匹配的类型。如果失败,我们尝试下一种类型。您必须确保从最严格的类型
int
(因为所有整数也可以解释为以
.0
结尾的浮点)开始,然后是
float
,然后是
str

将其放入函数中可以如下所示:

def check_type(input_string):
    try:
        int(input_string)
        return int
    except ValueError:
        pass
    try:
        float(input_string)
        return float
    except ValueError:
        pass
    return str
import csv

def isint(n):
    try:
        int(n)
        return True
    except:
        return False

def isfloat(n):
    try:
        float(n)
        return True
    except:
        return False

csvfile = list(csv.reader(open("csvfile.csv", "r"), delimiter=" "))
out = csv.writer(open("output.csv", "w"), delimiter=",")

for line in csvfile:
    row = []
    for variable in line:
        if isint(variable) == True:
            row.append('int')
        elif isfloat(variable) == True:
            row.append('float')
        else:
            row.append('str')
    out.writerow(row)
一些例子:

>>> check_type("10")
<class 'int'>
>>> check_type("10.1")
<class 'float'>
>>> check_type("A")
<class 'str'>
>>检查类型(“10”)
>>>检查类型(“10.1”)
>>>检查类型(“A”)
顺便说一下,不要被哪一个也是可接受的浮点输入弄糊涂了:

>>> check_type("1e1")
<class 'float'>
>>检查类型(“1e1”)

如果从对象创建数据帧,可以执行以下操作:

import pandas as pd
df = pd.read_csv('out146.txt', delim_whitespace=True)
for col in df: 
   df[col] = df[col].apply(lambda x: f"""'{re.findall(r"'(.*?)'",str(type(x))).pop()}'""") 
输出:

      id gender    age marital location income intelliscore emotiscore
0  'int'  'str'  'int'   'str'    'int'  'int'        'int'      'int'
1  'int'  'str'  'int'   'str'    'int'  'int'        'int'      'int'
2  'int'  'str'  'int'   'str'    'int'  'int'        'int'      'int'
3  'int'  'str'  'int'   'str'    'int'  'int'        'int'      'int'
4  'int'  'str'  'int'   'str'    'int'  'int'        'int'      'int'

假设输入CSV文件(
csvfile.CSV
)仅由一个空格字符(“”)分隔,您可以定义两种方法来确定每行上的每个元素是整数还是浮点(如果不是,则应为字符串)并使用

将所需结果写入新的
output.csv
文件的工作示例如下所示:

def check_type(input_string):
    try:
        int(input_string)
        return int
    except ValueError:
        pass
    try:
        float(input_string)
        return float
    except ValueError:
        pass
    return str
import csv

def isint(n):
    try:
        int(n)
        return True
    except:
        return False

def isfloat(n):
    try:
        float(n)
        return True
    except:
        return False

csvfile = list(csv.reader(open("csvfile.csv", "r"), delimiter=" "))
out = csv.writer(open("output.csv", "w"), delimiter=",")

for line in csvfile:
    row = []
    for variable in line:
        if isint(variable) == True:
            row.append('int')
        elif isfloat(variable) == True:
            row.append('float')
        else:
            row.append('str')
    out.writerow(row)

更好的是,为了简化代码,您可以对行中的变量执行:
:row.append(type(variable))
欢迎使用堆栈溢出:)请在合适的时候尝试使用代码格式。还有,我已经移除了你的“言语之花”。在你的问题中你不需要这个例如,见