【问题标题】:Python importing a text file and converting string to floatPython导入文本文件并将字符串转换为浮点数
【发布时间】:2021-05-29 15:29:24
【问题描述】:

我在将txt文件输入python时遇到了一些值错误。

名为“htwt.txt”的txt文件,包含以下数据:

Ht Wt

169.6 71.2

166.8 58.2

157.1 56

181.1 64.5

158.4 53

165.6 52.4

166.7 56.8

156.5 49.2

168.1 55.6

165.3 77.8

当我输入以下代码时,出现值错误。

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

import os


import statsmodels.api as sm

from statsmodels.formula.api import ols


os.chdir("/Users/James/Desktop/data/")

data1=np.loadtxt("htwt.txt") 

df1=pd.DataFrame(data1)

ValueError:无法将字符串转换为浮点数:'Ht'

我可以知道正确的代码应该是什么才能将其转换为数据框吗?谢谢。

【问题讨论】:

    标签: python string import floating txt


    【解决方案1】:

    熊猫read_csv就够了

    import pandas as pd
    import os
    os.chdir("/Users/James/Desktop/data/")
    
    df1 = pd.read_csv("htwt.txt",sep=' ')
    

    输出:

    >>> df1
          Ht    Wt
    0  169.6  71.2
    1  166.8  58.2
    2  157.1  56.0
    3  181.1  64.5
    4  158.4  53.0
    5  165.6  52.4
    6  166.7  56.8
    7  156.5  49.2
    8  168.1  55.6
    9  165.3  77.8
    

    检查类型:

    >>> df.info()
    <class 'pandas.core.frame.DataFrame'>
    RangeIndex: 10 entries, 0 to 9
    Data columns (total 2 columns):
     #   Column  Non-Null Count  Dtype  
    ---  ------  --------------  -----  
     0   Ht      10 non-null     float64
     1   Wt      10 non-null     float64
    dtypes: float64(2)
    memory usage: 288.0 bytes
    

    【讨论】:

      【解决方案2】:

      如上所述,pandas read_csv 有效,但如果您坚持使用 np.loadtxt,您可以跳过无法转换为浮点数的第一行。你可以这样做:

      data1 = np.loadtxt("htwt.txt", skiprows=1)
      

      【讨论】:

      • 请参阅 OP 对 Alexander 回答的评论。
      【解决方案3】:

      文本文件的第一行包含字母数字字符:“Ht Wt”。 这些字符不能转换为浮点数。 删除第一行应该没问题。

      【讨论】:

      • 嗨,Alexander,有什么方法不需要删除第一行而是在导入时将它们更改为列名?非常感谢!
      【解决方案4】:
      #for skipping of the first line
      file1 = open("hwwt.txt")
      
      lines = file1.readlines()[1:]
      for line in lines:
          print(line.rstrip())
      
      OUTPUT
      #otherwise you can use read_csv which is enough
      

      【讨论】:

      • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-25
      • 1970-01-01
      • 2019-07-10
      • 2017-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多