0

In R, to combine two vectors (or a vector with an element), it's just:

vector_1 <- c("a", "b", "c")
vector_2 <- c("d", "e", "f")

c(vector_1, vector_2)

[1] "a" "b" "c" "d" "e" "f"

How is this accomplished in python(/pandas)?

drigoangelo
  • 127
  • 1
  • 1
  • 11
stevec
  • 41,291
  • 27
  • 223
  • 311
  • 1
    Can you tell us what you have tried in Python so far? – Nannan AV May 02 '18 at 14:38
  • This was what I found, it looks so verbose I didn't want to sully my question with it: https://stackoverflow.com/questions/28943887/how-to-append-elements-to-a-numpy-array – stevec May 02 '18 at 14:38
  • 2
    List concatenation in Python is done with the operation "+" such as vector_1 + vector_2. – Kefeng91 May 02 '18 at 14:43

1 Answers1

2

Assuming you have

a = ["a", "b", "c"]
b = ["d", "e", "f"]

With Numpy you can do either of the following

c = np.concatenate([a, b])

>>> c
['a' 'b' 'c' 'd' 'e' 'f']

you can also use the more terse (but slightly slower)

c = np.r_[a,b]

>>> c
['a' 'b' 'c' 'd' 'e' 'f']

and if you are keeping it as a python list then you can just simply

c = a + b

>>> c
['a', 'b', 'c', 'd', 'e', 'f']
Grant Williams
  • 1,469
  • 1
  • 12
  • 24
  • Your answer tells how to concatenate 2 vectors, I figured out from your answer and Kefeng91's comment that to add a single element I can use: `a + ["random_string_element"]` - Thanks for the help! – stevec May 02 '18 at 14:51
  • 1
    your example seems to show you concatenating two vectors. If you are using numpy (with pandas for example) then the + symbol will attempt to do element-wise addition. The answer i've provided works for single elements just the same. You can also use `np.append()` but its built on np.concatenate – Grant Williams May 02 '18 at 14:55