[英]Import data from .txt file and define x and y variables in Python
I'm new to Python and I need to import data that is space separated. 我是Python的新手,我需要导入以空格分隔的数据。
The data looks something like this: 数据看起来像这样:
Title one
Title two
Title three
Title four
1.2944870E-03 7.1226442E-01
3.8834610E-03 8.3775342E-01
6.4724353E-03 1.0313828E+00
9.0614092E-03 7.7915078E-01
2.2006279E-02 1.1677371E+00
I need to skip the first 4 lines during import. 我需要在导入过程中跳过前4行。
So far I have this: 到目前为止,我有这个:
# Get .txt file
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename(filetypes=[("Two Column txt","*.txt"),("Any text file","*.*")])
# Read the data
import pandas as pd
data = pd.read_csv(file_path,skiprows=4)
After importing with pd.read_csv the data cames as [ x _amount of rows, 1 column]. 用pd.read_csv导入后,数据以[ x _行数,1列]的形式出现。 I would like to know if anyone can tell me how to separate this and assign the first column to X and the second column to Y
我想知道是否有人可以告诉我如何将其分开并将第一列分配给X ,将第二列分配给Y
Best Regards! 最好的祝福!
Since your file is space-separated then you should override the default comma-separated parsing using sep=' '
. 由于文件是用空格分隔的,因此您应该使用
sep=' '
覆盖默认的逗号分隔解析。 In order to provide your own headers you can use the header
and names
parameters: 为了提供自己的标题,可以使用
header
和names
参数:
data = pd.read_csv(file_path, sep=' ', skiprows=8, header=None, names=['X','Y'])
I was able to import the file with 我可以用导入文件
data = pd.read_csv(file_path, sep='\\s+', skiprows=4, header=None, names=['X','Y'])
Then I got the variables separated with: 然后我将变量分隔为:
X=data['X'] Y=data['Y']
Thank you all for the help. 谢谢大家的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.