如何将数据行拆分为python中以逗号分隔的列

时间:2017-10-14 18:09:06

标签: python numpy

我有一个以下格式的文本文件,我试图将其转换为行和列:

red,red,blue
blue,red,blue 
blue,blue,red

转换完成后,我想将上述内容存储在rows变量中:

row[0] # should return 'red red blue'
row[0][2] # should return 'blue'

到目前为止,我已经达到了:

file = open('myfile.txt')
for row in file:
    # do something here

但我不确定下一步该怎么做..有人可以帮忙吗?提前谢谢!

3 个答案:

答案 0 :(得分:4)

没有任何外部模块的解决方案:

output = []

with open('file.txt', 'r') as reading:
    file_input = reading.read().split('\n')

for row in file_input:
    output.append(row.split(','))

print(output)

答案 1 :(得分:3)

1.numpy solution :(因为numpy标签)

numpy.genfromtxt用于numpy数组:

import numpy as np
arr = np.genfromtxt('file.txt',dtype='str',delimiter=',')
print (arr)
[['red' 'red' 'blue']
 ['blue' 'red' 'blue']
 ['blue' 'blue' 'red']]

print (arr[0])
['red' 'red' 'blue']

print (arr[0][2])
blue

2.pandas解决方案

DataFrame用于import pandas as pd df = pd.read_csv('file.txt', header=None) print (df) 0 1 2 0 red red blue 1 blue red blue 2 blue blue red #select first row to Series print (df.loc[0]) 0 red 1 red 2 blue Name: 0, dtype: object #select value by index and column print (df.loc[0, 2]) blue 和选择值read_csv

nested list comprehension

3.pure python solutions

如果希望嵌套列表使用data = [[item for item in line.rstrip('\r\n').split(',')] for line in open('file.txt')] print (data) [['red', 'red', 'blue'], ['blue', 'red', 'blue'], ['blue', 'blue', 'red']]

csv

或使用模块import csv reader = csv.reader(open("file.txt"), delimiter=',') data = [word for word in [row for row in reader]] print (data) [['red', 'red', 'blue'], ['blue', 'red', 'blue'], ['blue', 'blue', 'red']]

print (data[0])
['red', 'red', 'blue']

print (data[0][2])
blue
SyncToyCmd

答案 2 :(得分:1)

pandas 模块的替代解决方案,适用于csv文件处理:

import pandas as pd

df = pd.read_csv('file.txt', header=None).T

print(df[0].tolist())    # ['red', 'red', 'blue']
print(df[0][2])          # blue