Johanna Marklund
Johanna Marklund

Reputation: 293

Combine np arrays in pandas

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?

Upvotes: 0

Views: 48

Answers (2)

pakpe
pakpe

Reputation: 5479

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]

Upvotes: 0

Anurag Dabas
Anurag Dabas

Reputation: 24314

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]

Upvotes: 2

Related Questions