[英]Python importing a text file and converting string to float
我在將 txt 文件輸入 python 時遇到了一些值錯誤。
txt 文件名為“htwt.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'
我可以知道正確的代碼應該是什么才能將其轉換為數據框嗎? 謝謝。
Pandas read_csv
就夠了
import pandas as pd
import os
os.chdir("/Users/James/Desktop/data/")
df1 = pd.read_csv("htwt.txt",sep=' ')
Output:
>>> 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
就像上面提到的 pandas read_csv
工作,但如果你堅持使用np.loadtxt
你可以跳過不能轉換為浮點數的第一行。 你可以做:
data1 = np.loadtxt("htwt.txt", skiprows=1)
文本文件的第一行包含字母數字字符:“Ht Wt”。 這些字符不能轉換為浮點數。 刪除第一行,你應該沒問題。
#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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.