2016-07-14 7 views
9

私は以下のDataFrameを持っています。私は "データ"列を複数の列に分割することが可能かどうか疑問に思っています。例えば、本から:この中パンダ、DataFrame:1つの列を複数の列に分割する

 
ID  Date  data 
6  21/05/2016 A: 7, B: 8, C: 5, D: 5, A: 8 
6  21/01/2014 B: 5, C: 5, D: 7 
6  02/04/2013 A: 4, D:7 
7  05/06/2014 C: 25 
7  12/08/2014 D: 20 
8  18/04/2012 A: 2, B: 3, C: 3, E: 5, B: 4 
8  21/03/2012 F: 6, B: 4, F: 5, D: 6, B: 4 

 
ID  Date  data       A B C D E F 
6  21/05/2016 A: 7, B: 8, C: 5, D: 5, A: 8 15 8 5 5 0 0 
6  21/01/2014 B: 5, C: 5, D: 7    0 5 5 7 0 0  
6  02/04/2013 B: 4, D: 7, B: 6    0 10 0 7 0 0 
7  05/06/2014 C: 25       0 0 25 0 0 0 
7  12/08/2014 D: 20       0 0 0 20 0 0 
8  18/04/2012 A: 2, B: 3, C: 3, E: 5, B: 4 2 7 3 0 5 0 
8  21/03/2012 F: 6, B: 4, F: 5, D: 6, B: 4 0 8 0 6 0 11 

私はこのpandas split string into columns、このpandas: How do I split text in a column into multiple rows?を試してみましたが、彼らは私の場合で働いていません。

EDIT複雑さのビットが「データ」の欄には「」繰り返され、したがって、これらの値が「A」列の下に合計される(最初の行で、例えば重複値を持つあり

2番目の表を参照してください)。

答えて

6

ここでキーに基づいて、辞書や集計値に文字列を変換することができます機能です。変換後は、それはpd.Series方法で結果を得ることは容易になります。

def str_to_dict(str1): 
    import re 
    from collections import defaultdict 
    d = defaultdict(int) 
    for k, v in zip(re.findall('[A-Z]', str1), re.findall('\d+', str1)): 
     d[k] += int(v) 
    return d 

pd.concat([df, df['dictionary'].apply(str_to_dict).apply(pd.Series).fillna(0).astype(int)], axis=1) 

enter image description here

3
df = pd.DataFrame([ 
     [6, "a: 1, b: 2"], 
     [6, "a: 1, b: 2"], 
     [6, "a: 1, b: 2"], 
     [6, "a: 1, b: 2"], 
    ], columns=['ID', 'dictionary']) 

def str2dict(s): 
    split = s.strip().split(',') 
    d = {} 
    for pair in split: 
     k, v = [_.strip() for _ in pair.split(':')] 
     d[k] = v 
    return d 

df.dictionary.apply(str2dict).apply(pd.Series) 

enter image description here

または:

pd.concat([df, df.dictionary.apply(str2dict).apply(pd.Series)], axis=1) 

enter image description here

+0

これはあなたのシリーズを与えるだろうし、複数の列に分割されません。 – user1124825

+0

@ user1124825答えを編集して文字列パーサを組み込みました。あなたの元々の質問は、 '' dictionary ''と書かれた列は辞書の列であると述べました。私はそれが真実だと思った。パーサーを適用することで、私の同じ答えがまだ成立しています。 – piRSquared

関連する問題