1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

特定文字で分割して列作成

Last updated at Posted at 2022-03-25
email
aaa@xxx.com
bbb@yyy.co.jp
ccc@zzz.ne.jp

上のようなデータフレームから、下のようなデータフレームを作りたい

email user domain
aaa@xxx.com aaa xxx.com
bbb@yyy.co.jp bbb yyy.co.jp
ccc@zzz.ne.jp ccc zzz.ne.jp

1. 特定文字列で分割

temp = df["email"].str.split("")
print(temp)
# 0      [aaa, xxx.com]
# 1    [bbb, yyy.co.jp]
# 2    [ccc, zzz.ne.jp]
# Name: email, dtype: object

2. 分割結果をデータフレームに拡張

temp = df["email"].str.split("", expand=True)
print(temp)
#      0          1
# 0  aaa    xxx.com
# 1  bbb  yyy.co.jp
# 2  ccc  zzz.ne.jp

3. 列名設定

temp = df["email"].str.split("", expand=True).set_axis(["user", "domain"], axis=1)
print(temp)
#   user     domain
# 0  aaa    xxx.com
# 1  bbb  yyy.co.jp
# 2  ccc  zzz.ne.jp

4. 元のデータフレームに結合

result = pd.concat([df, df["email"].str.split("", expand=True).set_axis(["user", "domain"], axis=1)], axis=1)
print(result)
#             email user     domain
# 0    aaa@xxx.com  aaa    xxx.com
# 1  bbb@yyy.co.jp  bbb  yyy.co.jp
# 2  ccc@zzz.ne.jp  ccc  zzz.ne.jp
1
2
0

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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?