Skip to content Skip to sidebar Skip to footer

Python: Create A Pandas Data Frame From A List

I am using the following code to create a data frame from a list: test_list = ['a','b','c','d'] df_test = pd.DataFrame.from_records(test_list, columns=['my_letters']) df_test The

Solution 1:

DataFrame.from_records treats string as a character list. so it needs as many columns as length of string.

You could simply use the DataFrame constructor.

In [3]: pd.DataFrame(q_list, columns=['q_data'])
Out[3]:
      q_data
011235440111161155262114909312312242549141319570255111373473

Solution 2:

In[20]: test_list = [['a','b','c'], ['AA','BB','CC']]

In[21]: pd.DataFrame(test_list, columns=['col_A', 'col_B', 'col_C'])
Out[21]: 
  col_A col_B col_C
0     a     b     c
1    AA    BB    CC

In[22]: pd.DataFrame(test_list, index=['col_low', 'col_up']).T
Out[22]: 
  col_low col_up
0       a     AA
1       b     BB
2       c     CC

Solution 3:

If you want to create a DataFrame from multiple lists you can simply zip the lists. This returns a 'zip' object. So you convert back to a list.

mydf = pd.DataFrame(list(zip(lstA, lstB)), columns = ['My List A', 'My List B'])

Post a Comment for "Python: Create A Pandas Data Frame From A List"