1

I have a text file (data.txt) like below:

name height  weight
    A   15.5    55.7
    B   18.9    51.6
    C   17.4    67.3
    D   11.4    34.5
    E   23.4    92.1

I want to make list in python for each column using pandas.

import pandas
with open (pandas.read_csv('data.txt')) as df:
    name= df.icol(0)
    height= df.icol(1)
    weight= df.icol(2)
    print (name)
    print (height)
    print (weight)

I also want to avoid the headers (name, height, weight) from the list.

print (df) provides as follows:

name\theight\tweight
0        A\t15.5\t55.7
1        B\t18.9\t51.6
2        C\t17.4\t67.3
3        D\t11.4\t34.5
4        E\t23.4\t92.1
4

4 回答 4

2

目前尚不清楚为什么要使用 pandas,因为您没有说明为什么要将它们专门放在列表中,所以这是一个使用的解决方案csv

import csv

with open('data.txt') as f:
    reader = csv.DictReader(f, delimiter='\t')
    rows = list(reader)

现在rows是一个字典列表,每个都有一个代表你的行的标题;获取您的每一列:

names = [i['name'] for i in rows]
heights = [float(i['height']) if i['height'] else 0.0 for i in rows]
weights = [float(i['weight']) if i['weight'] else 0.0 for i in rows]
于 2013-06-12T05:14:56.497 回答
1

尝试这样的事情:

import pandas
df = pandas.read_csv('data.txt')
# Assuming there's a columns with the headers 'name', 'height', 'weight'
name = list(df['name'])
height = list(df['height'])
weight = list(df['weight'])
print name
print height
print weight

在玩过这个例子并查看read_csv的文档后,认为这可能会起作用

如果你想对标题更有活力,你可以这样做

for k in df.keys():
    l = list(df[k])
    print l

它将遍历所有列并为它们创建列表。

于 2013-06-12T04:40:01.200 回答
0

要将 Series(例如,DataFrame 的列)转换为没有标题的普通 Python 值列表,请使用 Series 方法tolist()

In [9]: df
Out[9]: 
  name  height  weight
0    A    15.5    55.7
1    B    18.9    51.6
2    C    17.4    67.3
3    D    11.4    34.5
4    E    23.4    92.1

In [10]: name, height, weight = [df[col].tolist() for col in df]

In [11]: name
Out[11]: ['A', 'B', 'C', 'D', 'E']

等等。

于 2013-06-12T04:38:39.900 回答
0

因为上面的示例文本文件在第一列中有前导空格,所以必须使用以下内容来防止不正确的表导入:

df = pandas.read_csv("pandas_test.txt", sep=r"\s+")
于 2013-06-12T15:34:33.480 回答