LoginSignup
8
5

More than 5 years have passed since last update.

Python の文字列配列の各末尾に文字列を付加する方法

Last updated at Posted at 2017-12-23

※ 2017-12-24 shiracamus さんの指摘をうけて大幅に修正しました。

したいこと

下記 A, B, C それぞれの値の末尾に 1 という文字を加えたい。

>>> A = ['a', 'b']
>>> B = pandas.Series(['a', 'b'])
>>> C = numpy.array(['a', 'b'])
ほしい形
['a1', 'b1']

結論

リストの場合
>>> A = ['a', 'b']
>>> [s + '1' for s in A]
['a1', 'b1']
Seriesの場合
>>> B = pandas.Series(['a', 'b'])
>>> B + '1'  # + 演算子で実現できる
0    a1
1    b1
dtype: object
numpy.arrayの場合
>>> C = numpy.array(['a', 'b'])
>>> C.astype(object) + '1'  # dtype=object にすれば + 演算子で実現できる
array(['a1', 'b1'], dtype=object)

派生:配列同士を結合する場合

リストの場合
>>> A1 = ['a', 'b']
>>> A2 = ['1', '2']
>>> [a + b for a, b in zip(A1, A2)]   # zip を使う
['a1', 'b2']
Seriesの場合
>>> B1 = pandas.Series(['a', 'b'])
>>> B2 = pandas.Series(['1', '2'])
>>> B1 + B2  # 前述と同様
0    a1
1    b2
dtype: object
numpy.arrayの場合
>>> C1 = numpy.array(['a', 'b'])
>>> C2 = numpy.array(['1', '2'])
>>> C1.astype(object) + C2.astype(object)  # 前述と同様
array(['a1', 'b2'], dtype=object)

注意

通常の配列(リスト)と array-like は挙動がかなり違うので常に意識すること。

In(配列の場合)
>>> A1 = ['a', 'b']
>>> A2 = ['1', '2']
>>> A1 + A2
['a', 'b', '1', '2']

このように配列(リスト)を単純に + すると縦方向に連結される。

8
5
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5