Dictionary column in pandas dataframe

后端 未结 3 1807
伪装坚强ぢ
伪装坚强ぢ 2020-12-24 00:51

I\'ve got a csv that I\'m reading into a pandas dataframe. However one of the columns is in the form of a dictionary. Here is an example:

ColA, ColB, ColC, C         


        
3条回答
  •  醉梦人生
    2020-12-24 01:08

    What about something like:

    import pandas as pd
    
    # Create mock dataframe
    df = pd.DataFrame([
        [20, 30, {'ab':1, 'we':2, 'as':3}, 'String1'],
        [21, 31, {'ab':4, 'we':5, 'as':6}, 'String2'],
        [22, 32, {'ab':7, 'we':8, 'as':9}, 'String2'],
    ], columns=['Col A', 'Col B', 'Col C', 'Col D'])
    
    # Create dataframe where you'll store the dictionary values
    ddf = pd.DataFrame(columns=['AB','WE','AS'])
    
    # Populate ddf dataframe
    for (i,r) in df.iterrows():
        e = r['Col C']
        ddf.loc[i] = [e['ab'], e['we'], e['as']]
    
    # Replace df with the output of concat(df, ddf)
    df = pd.concat([df, ddf], axis=1)
    
    # New column order, also drops old Col C column
    df = df[['Col A', 'Col B', 'AB', 'WE', 'AS', 'Col D']]
    
    print(df)
    

    Output:

       Col A  Col B  AB  WE  AS    Col D
    0     20     30   1   2   3  String1
    1     21     31   4   5   6  String2
    2     22     32   7   8   9  String2
    

提交回复
热议问题