Reputation: 2332
I want to convert this list into a pandas dataframe
my_list = [1,2,3,4,5,6,7,8,9]
The dataframe would have 3 columns and 3 rows. I try using
df = pd.DataFrame(my_list, columns = list("abc"))
but it doesn't seem to be working for me.
Upvotes: 31
Views: 172997
Reputation: 23381
If you came here looking for a way to convert a Python list into a pandas DataFrame, you may be facing one of the following problems:
df = pd.DataFrame(my_list)
# or
df = pd.DataFrame({'col1': my_list})
col_names = ['col1', 'col2']
df = pd.DataFrame(my_list, columns=col_names)
df = pd.DataFrame([my_list])
len(col_names) == len(my_list)
must be True.
col_names = ['col1', 'col2', 'col3']
df = pd.DataFrame(dict(zip(col_names, my_list)))
iter()
and zip()
functions and cast to a DataFrame.
col_names = ['col1', 'col2', 'col3']
df = pd.DataFrame(zip(*[iter(my_list)]*len(col_names)), columns=col_names)
col_names = ['col1', 'col2', 'col3']
df = pd.DataFrame(zip(*[iter(my_list)]*(len(my_list)//len(col_names))), index=col_names).T
Upvotes: 2