0

I have two columns and I would like to create a list for each row. Thus, each list would contain two values; the values of each column for that specific row. For example:

A B
1 2
3 4
5 6

I would like to have a list for each row of values i.e. [1,2], [3,4], [5,6]

Could you help me with this one please?

sacuL
  • 49,704
  • 8
  • 81
  • 106
stosxri
  • 51
  • 5
  • Possible duplicate of [Concate two dataframes based on no of rows](https://stackoverflow.com/questions/51327984/concate-two-dataframes-based-on-no-of-rows) – Igor S Jul 13 '18 at 17:55
  • @IgorS this is definitely not a duplicate of that link – pault Jul 13 '18 at 21:08
  • Possible duplicate of [Convert a row in pandas into list](https://stackoverflow.com/questions/19585280/convert-a-row-in-pandas-into-list) – pault Jul 13 '18 at 21:09

2 Answers2

3

You can use this if you want to keep it in a dataframe:

df['new'] = df.values.tolist()

>>> df
   A  B     new
0  1  2  [1, 2]
1  3  4  [3, 4]
2  5  6  [5, 6]

Otherwise, if you just want the lists, just use:

df.values.tolist()

[[1, 2], [3, 4], [5, 6]]

Or even just df.values (though the result will be a numpy array, as opposed to a list of lists):

>>> df.values
array([[1, 2],
       [3, 4],
       [5, 6]])
sacuL
  • 49,704
  • 8
  • 81
  • 106
0

If you had the following DataFrame:

print(df)
#   A  B
#0  1  2
#1  3  4
#2  5  6

One way to get the rows as lists is by using to_records():

print([list(x) for x in df.to_records(index=False)])
#[[1, 2], [3, 4], [5, 6]]

Or if you wanted to include the index:

print([list(x) for x in df.to_records(index=True)])
#[[0, 1, 2], [1, 3, 4], [2, 5, 6]]
pault
  • 41,343
  • 15
  • 107
  • 149