cna
cna

Reputation: 337

convert list of dict to list of list python from dataframe

As title.

I have a dataframe column called column1:

column1
[ {'x': 1, 'y': 0},{'x': 2, 'y': 0},{'x': 4, 'y': 5} ]
[ {'x': 1, 'y': 0},{'x': 0, 'y': 5},{'x': 2, 'y': 0},{'x': 4, 'y': 5} ]

Every row is a list of dictionary. I want to transform to list of list like this :

column2
[[0,1],[0,2],[5,4]]
[[0,1],[5,0],[0,2],[5,4]]

Note that the position of x and y are reversed to y and x after transformed.

This is my attempt :

[[x['column2']] for x in df['column1']]

Receiving error "TypeError: list indices must be integers or slices, not str".

I changed to :

[[x[0]] for x in df['column1']]

I'm not getting the output I want.

Upvotes: 0

Views: 52

Answers (2)

sushanth
sushanth

Reputation: 8302

try this,

import pandas as pd

df = pd.DataFrame({"column1": [[{'x': 1, 'y': 0}, {'x': 2, 'y': 0}, {'x': 4, 'y': 5}],
                               [{'x': 1, 'y': 0}, {'x': 0, 'y': 5}, {'x': 2, 'y': 0}, {'x': 4, 'y': 5}]]})

df['column2'] = df['column1'].apply(lambda x: [list(v.values())[::-1] for v in x])

0            [[0, 1], [0, 2], [5, 4]]
1    [[0, 1], [5, 0], [0, 2], [5, 4]]

Name: column2, dtype: object

Upvotes: 2

yasser
yasser

Reputation: 91

you can use dict values . this is an example

list1 = [ {'x': 1, 'y': 0},{'x': 2, 'y': 0},{'x': 4, 'y': 5} ]
list2 = []
for dic in list1:
    list2.append(list(dic.values()))
print(list2)

Upvotes: 0

Related Questions