如何从python中的txt文件中读取特定列? [英] How can I read specific colums from a txt file in python?

查看:223
本文介绍了如何从python中的txt文件中读取特定列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 .txt 数据集,如下所示:

I have a .txt dataset like this:

user_000044 2009-04-24  13:47:07    Spandau Ballet  Through The Barricades 

我必须阅读最后两列,Spandau Ballet 是独一无二的,而《Through the Barricades》也是独一无二的.我该怎么做?

I have to read the last two colums, Spandau Ballet as unique and Through the Barricades as unique. How can I do this?

需要创建两个数组,artists =[]tracks = [],其中我将数据放入循环中,但我无法定义部分一行中的文本.

In need to create two array, artists =[] and tracks = [] in which I put data in a loop, but I can't define the portion of text in a line.

有人可以帮助我吗?

推荐答案

使用 pandas 模块加载 .txt 的内容可能会更好进入熊猫 DataFrame 并从那里继续.如果你不熟悉它......DataFrame 与使用 Python 所能获得的 Excel 表格非常接近.pandas 将为您处理读取行,因此您不必编写自己的循环.

You are probably better off with using the pandas-module to load the content of the .txt into a pandas DataFrame and proceed from there. If you're unfamiliar with it...a DataFrame is as close to an Excelsheet as it can get with Python. pandas will handle reading the lines for you so you don't have to write your own loop.

假设您的文本文件是四列,以制表符分隔,如下所示:

Assuming your textfile is four column, tab-separated, this would look like:

# IPython for demo:
import pandas as pd

df = pd.read_csv('ballet.txt', sep='\t', header=None, names=['artists', 'tracks'], usecols=[2, 3])
# usecols here limits the Dataframe to only consist the 3rd and 4th column of your .txt

您的 DataFrame 可能如下所示:

Your DataFrame then could look like:

df
# Out: 
          artists                  tracks
0  Spandau Ballet  Through The Barricades
1   Berlin Ballet               Swan Lake

按列名访问单列:

df.artists  # or by their index e.g. df.iloc[:, 0]
# Out: 
0    Spandau Ballet
1     Berlin Ballet
Name: 2, dtype: object

此时您仍然可以将数据放入数组中,但如果您知道替代方案,我想不出您真的想要这样做的原因.

You can still put the data into an array at this point, but I can't think of a reason you really wanna do this if you're aware of the alternatives.

这篇关于如何从python中的txt文件中读取特定列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆