Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append values from dataframe column to list

I have a dataframe with several columns, and I want to append to an empty list the values of one column, so that the desired output would be the following:

empty_list = [value_1,value_2,value_3...]

I have tried the following:

df = pd.DataFrame({'country':['a','b','c','d'],
      'gdp':[1,2,3,4],
      'iso':['x','y','z','w']})
a_list = []

a_list.append(df['iso'])
a_list.append(df['iso'].values)
a_list.append(df['iso'].tolist())

Either way, I get a list with lists, numpy arrays or series inside it, and I would like to have directly the records.

like image 597
Javier Lopez Tomas Avatar asked May 27 '19 07:05

Javier Lopez Tomas


1 Answers

You could try this script if you need to append one column only:

a_list = df['iso'].tolist()

For extending a list by appending elements from the iterable, use extend:

a_list = []
a_list.extend(df['iso'].tolist())
a_list.extend(df['country'].tolist())
print (a_list)
['x', 'y', 'z', 'w', 'a', 'b', 'c', 'd']

Another solution is to use numpy.ravel with transpose:

a_list = df[['iso','country']].values.T.ravel().tolist()
print (a_list)
['x', 'y', 'z', 'w', 'a', 'b', 'c', 'd']
like image 64
jezrael Avatar answered Oct 03 '22 01:10

jezrael