【问题标题】:Iterating through a CSV to determine the type of data遍历 CSV 以确定数据类型
【发布时间】:2020-04-13 08:29:38
【问题描述】:

所以我正在做 Python 入门课程,我需要做以下事情: 有一个 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

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

【问题讨论】:

    标签: python loops file csv


    【解决方案1】:

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

    if type(variable) == str:
    

    【讨论】:

    • 更好的是,为了简化您的代码,您可以这样做:for variable in line: row.append(type(variable))
    【解决方案2】:

    你熟悉 Python 中的 EAFP 原理吗?如果没有,看看这个问题:What is the EAFP principle in Python?

    我们可以在这里做类似的事情:您可以使用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
    

    一些例子:

    >>> check_type("10")
    <class 'int'>
    >>> check_type("10.1")
    <class 'float'>
    >>> check_type("A")
    <class 'str'>
    

    顺便说一句,不要对scientific notation 感到困惑,这也是可接受的浮点输入:

    >>> check_type("1e1")
    <class 'float'>
    

    【讨论】:

      【解决方案3】:

      如果你从你的对象创建一个 pandas 数据框,你可以这样做:

      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'
      

      【讨论】:

        【解决方案4】:

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

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

        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)
        

        【讨论】:

          猜你喜欢
          • 2021-01-11
          • 2018-04-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-05-26
          • 1970-01-01
          • 2015-10-22
          • 2014-06-14
          相关资源
          最近更新 更多