2016-07-14 91 views
9

我有以下DataFrame。我想知道是否有可能將「數據」列分成多列。例如,從這個:Pandas,DataFrame:將一列分成多列

 
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」是重複的,因此,這些值是在「A」列下總結(請參閱第二張表格)。

回答

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我編輯了包含字符串解析器的答案。你原來的問題提到了標有''字典''的專欄是一列字典。我認爲這是事實。通過應用解析器,我的相同答案仍然成立。 – piRSquared