Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert list to row dataframe with Pandas

I have a list of items like this:

A = ['1', 'd', 'p', 'bab', '']

My goal is to convert such list into a dataframe of 1 row and 5 columns. If I type pd.DataFrame(A) I get 5 rows and 1 column. What should I do in order to get the result I want?

like image 707
Federico Gentile Avatar asked Feb 13 '17 11:02

Federico Gentile


People also ask

How do I turn a list into a DataFrame row?

Method 1: Using T function This is known as the Transpose function, this will convert the list into a row. Here each value is stored in one column. Example: Python3.

How do you split a list into a row in Python?

Convert each string of names to a list and use Pandas explode() function to split the list by each element and create a new row for each of them.


2 Answers

You can use:

df = pd.DataFrame([A])
print (df)
   0  1  2    3 4
0  1  d  p  bab  

If all values are strings:

df = pd.DataFrame(np.array(A).reshape(-1,len(A)))
print (df)

   0  1  2    3 4
0  1  d  p  bab  

Thank you AKS:

df = pd.DataFrame(A).T
print (df)
   0  1  2    3 4
0  1  d  p  bab  
like image 199
jezrael Avatar answered Oct 23 '22 18:10

jezrael


This is somewhat peripheral to your particular issue, but I figured I would post it in case it helps someone else out.

To convert a list of lists (and give each column a name), just pass the list to the data attribute (along with your desired column names) when instantiating the new dataframe, like so:

my_python_list = [['foo1', 'bar1'],
                  ['foo2', 'bar2']]
new_df = pd.DataFrame(columns=['my_column_name_1', 'my_column_name_2'], data=my_python_list)

result:

  my_column_name_1 my_column_name_2
0             foo1             bar1
1             foo2             bar2
like image 31
Tom Chapin Avatar answered Oct 23 '22 17:10

Tom Chapin