0

I have this:

cars= pd.DataFrame({'x': [[1,2,3],[2,3,4],[5,6,7]],
                    'y': [[8,9,7],[9,8,1],[3,4,1]]})

       x          y
0  [1, 2, 3]  [8, 9, 7]
1  [2, 3, 4]  [9, 8, 1]
2  [5, 6, 7]  [3, 4, 1]

I want this:

      x          y            combined
0  [1, 2, 3]  [8, 9, 7]  [1, 2, 3, 8, 9, 7]
1  [2, 3, 4]  [9, 8, 1]  [2, 3, 4, 9, 8, 1]
2  [5, 6, 7]  [3, 4, 1]  [5, 6, 7, 3, 4, 1]

I have tried this, and it does not work:

cars['combined']=pd.concat([cars['x'],cars['y']])
cars['combined']=cars['x'].append(cars['y'])
cars['combined']=pd.concat((cars['x'],cars['y']),axis=0)
cars['combined']=cars['x'].join(cars['y'])

How do I combine these?

2 Answers2

2

Just use this:-

cars['combined']=cars['x']+cars['y']

Now if you print cars you will get your desired output:

    x               y        combined
0   [1, 2, 3]   [8, 9, 7]   [1, 2, 3, 8, 9, 7]
1   [2, 3, 4]   [9, 8, 1]   [2, 3, 4, 9, 8, 1]
2   [5, 6, 7]   [3, 4, 1]   [5, 6, 7, 3, 4, 1]
Anurag Dabas
  • 23,866
  • 9
  • 21
  • 41
  • 1
    Works very well, and I am familiar with this notation. – Johanna Marklund Mar 27 '21 at 14:28
  • It's the better way then accessing columns by `.` notation – Anurag Dabas Mar 27 '21 at 14:31
  • @AnuragDabas Why? – pakpe Mar 27 '21 at 14:41
  • In my real data I have a Series with ndarray generated from an apply comand. The apply comand gave me a Series with ndarray, just like in my simplified question. I get the "operands could not be broadcast together with shapes (9,) (3,)" error. Do you know what I am doing wrong? – Johanna Marklund Mar 27 '21 at 14:50
  • yes the shape of arrays are different so due to this you are getting this error – Anurag Dabas Mar 27 '21 at 14:59
  • @pakpe kindly have a look on https://www.dataschool.io/pandas-dot-notation-vs-brackets/ and https://stackoverflow.com/questions/41130255/what-is-the-difference-between-using-squared-brackets-or-dot-to-access-a-column – Anurag Dabas Mar 27 '21 at 15:19
  • 1
    @AnuragDabas I did. None of those issues apply to this question. When it is possible to use dot notation, it provides for a much cleaner code that’s faster to write. – pakpe Mar 27 '21 at 15:27
  • @pakpe Yeah you are right...I am saying this generally not only for this question....apart from advantage and disadvantage...it's per the convience of user some likes bracket notation and some like dot notation as it is provides a much cleaner code :) – Anurag Dabas Mar 27 '21 at 15:32
0

Here:

cars['combined'] = cars.x + cars.y
print(cars)

           x          y            combined
0  [1, 2, 3]  [8, 9, 7]  [1, 2, 3, 8, 9, 7]
1  [2, 3, 4]  [9, 8, 1]  [2, 3, 4, 9, 8, 1]
2  [5, 6, 7]  [3, 4, 1]  [5, 6, 7, 3, 4, 1]
pakpe
  • 5,391
  • 2
  • 8
  • 23