读取数据作为python中的列表?

时间:2018-11-13 14:44:15

标签: python pandas list csv

     x       y
[133,28,23] female
[157,22,87] male
[160,33,77] male
[122,87,20] female
[120,22,20] female

这是我book.csv文件中的数据。

>>fd=pandas.read_csv("C://users/admin/Desktop/Book1.csv")
>>l1=[h for h in fd.x]

在执行以下命令之后,l1存储此值:

['[133,28,23]', '[157,22,87]', '[160,33,77]', '[122,87,20]', '[120,22,20]']

以下输出是列表格式的字符串,但我想要这样的嵌套列表:

[[133,28,23],[157,22,87],[160,33,77],[122,87,20],[120,22,20]]

我需要进行哪些更改?

3 个答案:

答案 0 :(得分:2)

您可以使用ast.literal_eval执行以下操作:

import pandas as pd
import ast

data = [['[133,28,23]', 'female'],
        ['[157,22,87]', 'male'],
        ['[160,33,77]', 'male'],
        ['[122,87,20]', 'female'],
        ['[120,22,20]', 'female']]

df = pd.DataFrame(data=data, columns=['x', 'y'])
df['x'] = df['x'].apply(ast.literal_eval)
result = df['x'].tolist()

print(result)

输出

[[133, 28, 23], [157, 22, 87], [160, 33, 77], [122, 87, 20], [120, 22, 20]]

答案 1 :(得分:0)

您可以使用json:

>> import json
>> fd=pandas.read_csv("C://users/admin/Desktop/Book1.csv")
>> l1=[json.loads(h) for h in fd.x]
[[133,28,23],[157,22,87],[160,33,77],[122,87,20],[120,22,20]]

或ast

>> import ast
>> fd=pandas.read_csv("C://users/admin/Desktop/Book1.csv")
>> l1=[ast.literal_eval(h) for h in fd.x]
>> [[133,28,23],[157,22,87],[160,33,77],[122,87,20],[120,22,20]]

答案 2 :(得分:0)

一种简单的方法,如果您不想诉诸ast(例如,避免解析不是列表的内容):

from io import StringIO

inp = """     x       y
[133,28,23] female
[157,22,87] male
[160,33,77] male
[122,87,20] female
[120,22,20] female"""

# Read data
df = pd.read_csv(StringIO(inp), delim_whitespace=True, header=0)
# Remove brackets, split and convert to int
df.x = df.x.map(lambda el: list(map(int, el.strip()[1:-1].split(','))))
# Print
l1 = [h for h in df.x]
print(l1)

输出:

[[133, 28, 23], [157, 22, 87], [160, 33, 77], [122, 87, 20], [120, 22, 20]]