Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create nested list from Pandas dataframe

Tags:

python

pandas

i have a simple pandas dataframe with two columns. i would like to generate a nested list of those two columns.

geo = pd.DataFrame({'lat': [40.672304, 40.777169, 40.712196], 
                'lon': [-73.935385, -73.988911, -73.957649]})

my solution to this problem is the following:

X = [[i] for i in geo['lat'].tolist()]
Y = [i for i in geo['lon'].tolist()]

for key, value in enumerate(X):
    X[key].append(Y[key])

however, i feel there must be a better way than this.

thanks!

like image 992
phillyooo Avatar asked Oct 22 '16 22:10

phillyooo


People also ask

How do you make a nested list a DataFrame in Python?

Converting the lists to a DataFrame To create a DataFrame, we will first assign the newly created list to pd. DataFrame and assign column name as 'station'. We will also add a column that contains the station addresses.

Can a DataFrame be nested?

Or more commonly, we can create nested data frames using tidyr::nest() . df %>% nest(x, y) specifies the columns to be nested; i.e. the columns that will appear in the inner data frame. Alternatively, you can nest() a grouped data frame created by dplyr::group_by() .

Can you put a list in a Pandas DataFrame?

You can insert a list of values into a cell in Pandas DataFrame using DataFrame.at() , DataFrame. iat() , and DataFrame. loc() methods.


1 Answers

pandas is built on top of numpy. A DataFrame stores its values in a numpy array, which has a tolist method.

>>> geo = pd.DataFrame({'lat': [40.672304, 40.777169, 40.712196],
    ...:                 'lon': [-73.935385, -73.988911, -73.957649]})
    ...:
>>> geo.values
>>>
array([[ 40.672304, -73.935385],
       [ 40.777169, -73.988911],
       [ 40.712196, -73.957649]])
>>>
>>> geo.values.tolist()
[[40.672304, -73.935385], [40.777169, -73.988911], [40.712196, -73.957649]]
like image 72
timgeb Avatar answered Oct 18 '22 23:10

timgeb