1
4

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 3 years have passed since last update.

【pandas】文字列をDataFrameに展開

Posted at

かゆいところに手が届くpandasレシピ集No.1

かゆいこと

「カテゴリ名(index)」と「値(value)」が文字列として1つの要素となってしまっている配列・DataFrameをなんとかしたい。
各カテゴリ(index)をcolumn名とする列に値を割り振ろう。

ID クソデカ文字列
0 A 0, B 1, C 2
1 B 3, D 4
2 A 5, C 6
3 C 7, D 8

↑この↑クソデカ文字列を↓こう↓したい。

ID A B C D
0 0 1 2 0
1 0 3 0 4
2 5 0 6 0
3 0 0 7 8

レシピ

各カテゴリは既知とします。
未知の場合、カテゴリのリストを作成してください。

str_to_dataframe.py
import numpy as np
import pandas as pd

def str_to_dict(x):
    dic = {'A' : 0, 'B' : 0, 'C' : 0, 'D' : 0}
    for xx in x.split(","):
        xxs = xx.split(" ")
        dic[xxs[-2]] = int(xxs[-1])
    return dic

temp = df["クソデカ文字列"].apply(lambda x : pd.Series(str_to_dataframe(x)))
df = pd.concat((df, temp), axis=1)

これは早い!

1
4
1

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
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?