Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dataframe pandas how to pass list as columns

I have two lists, such as:

list_columns = ['a','b','c','d','e','f','g','h','k','l','m','n']

and a list of values

list_values = [11,22,33,44,55,66,77,88,99,100, 111, 222]

I want to create a Pandas dataframe using list_columns as columns.

I tried with df = pd.DataFrame(list_values, columns=list_columns) but it doesn't work

I get this error: ValueError: Shape of passed values is (1, 12), indices imply (12, 12)

like image 691
Alex Avatar asked Jan 18 '19 18:01

Alex


2 Answers

A dataframe is a two-dimensional object. To reflect this, you need to feed a nested list. Each sublist, in this case the only sublist, represents a row.

df = pd.DataFrame([list_values], columns=list_columns)

print(df)

#     a   b   c   d   e   f   g   h   k    l    m    n
# 0  11  22  33  44  55  66  77  88  99  100  111  222

If you supply an index with length greater than 1, Pandas broadcasts for you:

df = pd.DataFrame([list_values], columns=list_columns, index=[0, 1, 2])

print(df)

#     a   b   c   d   e   f   g   h   k    l    m    n
# 0  11  22  33  44  55  66  77  88  99  100  111  222
# 1  11  22  33  44  55  66  77  88  99  100  111  222
# 2  11  22  33  44  55  66  77  88  99  100  111  222
like image 71
jpp Avatar answered Sep 23 '22 14:09

jpp


If I understand your question correctly just wrap list_values in brackets so it's a list of lists

list_columns = ['a','b','c','d','e','f','g','h','k','l','m','n']
list_values = [[11,22,33,44,55,66,77,88,99,100, 111, 222]]

pd.DataFrame(list_values, columns=list_columns)
    a   b   c   d   e   f   g   h   k    l    m    n
0  11  22  33  44  55  66  77  88  99  100  111  222
like image 42
dsbailey Avatar answered Sep 24 '22 14:09

dsbailey