Pandas, DataFrame: Splitting one column into multiple columns

后端 未结 2 939
花落未央
花落未央 2021-02-13 14:27

I have the following DataFrame. I am wondering whether it is possible to break the data column into multiple columns. E.g., from this:

ID       Date             


        
2条回答
  •  眼角桃花
    2021-02-13 14:51

    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)
    

    Or:

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

提交回复
热议问题