Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a dataframe from list with different length [duplicate]

Here I got many list with different length, like a=[1,2,3] and b=[2,3]

I would like to generate a pd.DataFrame from them, by padding nan at the end of list, like this:

   a  b
1  1  2 
2  2  3
3  3  nan

Any good idea to help me do so?

like image 819
Garvey Avatar asked Apr 18 '18 04:04

Garvey


People also ask

How do you create a repeated DataFrame?

To create a data frame with a column having repeated values, we simply need to use rep function and we can repeat the values in a sequence of the values passed or repeating each value a particular number of times.

How do you convert multiple series to DataFrame?

You can create a DataFrame from multiple Series objects by adding each series as a columns. By using concat() method you can merge multiple series together into DataFrame. This takes several params, for our scenario we use list that takes series to combine and axis=1 to specify merge series as columns instead of rows.

How do I create a data frame from two lists?

Using zip to append lists and then building the DF If we want to get each list data into different columns, then we have to define a list of lists first. Each list will represent a row in the DataFrame. The super handy zip function allows us to stitch the lists together.

How do you clone a data frame?

To copy Pandas DataFrame, use the copy() method. The DataFrame. copy() method makes a copy of the provided object's indices and data. The copy() method accepts one parameter called deep, and it returns the Series or DataFrame that matches the caller.


1 Answers

Use

In [9]: pd.DataFrame({'a': pd.Series(a), 'b': pd.Series(b)})
Out[9]:
   a    b
0  1  2.0
1  2  3.0
2  3  NaN

Or,

In [10]: pd.DataFrame.from_dict({'a': a, 'b': b}, orient='index').T
Out[10]:
     a    b
0  1.0  2.0
1  2.0  3.0
2  3.0  NaN
like image 113
Zero Avatar answered Oct 21 '22 19:10

Zero