Rusher
Rusher

Reputation: 1

Read data as list in python?

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

This is the data that i have in my book.csv file.

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

After following commands, l1 stores this value:

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

The following output is string in list format, but i want nested list like this:

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

What changes do I need to make?

Upvotes: 1

Views: 76

Answers (3)

javidcf
javidcf

Reputation: 59691

One simple way, if you don't want to resort to ast (for example to avoid parsing something that is not a list):

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)

Output:

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

Upvotes: 0

hecvd
hecvd

Reputation: 668

You can use 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]]

Or 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]]

Upvotes: 0

Dani Mesejo
Dani Mesejo

Reputation: 61910

You could do the following, using 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)

Output

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

Upvotes: 2

Related Questions