Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to covert a list of lists into dataframe and make the first element of the lists as the index

Tags:

python

pandas

The sample data of mine may be seen here:

data=[['Australia',100],['France',200],['Germany',300],['America',400]]

What I expect may be the dataframe like this:

           volume
Australia     100
France        200
Germany       300
America       400

And I've tried the following:

pd.DataFrame(data,columns=['Country','Volume']) 
     Country  Volume
0  Australia     100
1     France     200
2    Germany     300
3    America     400

pd.DataFrame.from_items()

Howerver, I still can't get the expected result?

Is there a possible way that I can get the expected pandas dataframe structure? Thanks for all your kindly checking in advance.

like image 978
Tian Wolf Avatar asked May 06 '16 09:05

Tian Wolf


People also ask

How do I get the first column in a DataFrame list?

In this article, we will discuss different ways to get or select the first column of dataframe as a series or list object. Use iloc[] to select first column of pandas dataframe. Use [] to select first column of pandas dataframe. Use head() to select first column of pandas dataframe.

Can we create DataFrame from list?

The pandas DataFrame can be created by using the list of lists, to do this we need to pass a python list of lists as a parameter to the pandas. DataFrame() function. Pandas DataFrame will represent the data in a tabular format, like rows and columns.


1 Answers

You can call set_index on the result of the dataframe:

In [2]:
data=[['Australia',100],['France',200],['Germany',300],['America',400]]
pd.DataFrame(data,columns=['Country','Volume']).set_index('Country') 

Out[2]:
           Volume
Country          
Australia     100
France        200
Germany       300
America       400
like image 51
EdChum Avatar answered Sep 30 '22 07:09

EdChum