sheperdgirl
sheperdgirl

Reputation: 25

How to concatenate 2 columns,which contains np arrays, into a new column in dataframe

original dataframe

A                      B
np.array([1, 2, 3])    np.array([4, 5, 6])
np.array([7, 8, 9])    np.array([9, 10, 11])

wish it to be

A                      B                         C
np.array([1, 2, 3])    np.array([4, 5, 6])       np.array([1, 2, 3, 4, 5, 6])
np.array([7, 8, 9])    np.array([9, 10, 11])     np.array([7, 8, 9, 9, 10, 11])

How to achieve that?

Upvotes: 0

Views: 70

Answers (1)

Zero
Zero

Reputation: 76927

Option 1:

In [66]: df['C'] = [np.append(*x) for x in df[['A', 'B']].values]

In [67]: df
Out[67]:
           A            B                     C
0  [1, 2, 3]    [4, 5, 6]    [1, 2, 3, 4, 5, 6]
1  [7, 8, 9]  [9, 10, 11]  [7, 8, 9, 9, 10, 11]

Option 2: df['C'] = [np.concatenate(x) for x in df[['A', 'B']].values]

Option 3: df['C'] = map(np.concatenate, df[['A', 'B']].values)

Test

In [69]: df.loc[0, 'C']
Out[69]: array([1, 2, 3, 4, 5, 6])

Upvotes: 2

Related Questions