简体   繁体   English

从.txt文件导入数据并在Python中定义x和y变量

[英]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: 为了提供自己的标题,可以使用headernames参数:

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.

相关问题 如何从CSV文件中提取数据列并将其定义为x和y变量,然后使用pylab在python中绘制它们? - How can I extract columns of data from a CSV file and define them as x and y variables, then plot them in python using pylab? 如何读取 2 列 of.txt 文件并将其存储在 python 的 x 和 y 变量中 - How to read 2 columns of .txt file & store it in x & y variables in python 使用txt文件(Python)中的数据绘制日期和时间(x轴)与值(y轴)的关系 - Plot date and time (x axis) versus a value (y axis) using data from txt file (Python) 如何使用 python 中 txt 文件中的 xy 数据 plot 粒子的轨迹? - How to plot the trajectory of a particle using x y data from a txt file in python? 从txt文件将数据导入Python - Import data into Python from txt file 从“混乱”的 txt 文件中提取 x 和 y 数据 - extracting x and y data from a "messy" txt file 使用txt文件在python中定义多个变量 - Using a txt file to define multiple variables in python 使用python脚本在txt文件中定义变量 - define variables in the txt file using python script Python 'from x import y' vs 'from.x import y' - Python 'from x import y' vs 'from .x import y' 使用txt文件(Python)中的数据绘制日期和时间(x轴)与值(y轴)(仅用空格分隔的列) - Plot date and time (x axis) versus a value (y axis) using data from txt file (Python) (columns separated only by spaces)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM