Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

python - parsing a dictionary in a pandas dataframe cell into new row cells (new columns)

I have a Pandas Dataframe that contains one column containing cells containing a dictionary of key:value pairs, like this:

{"name":"Test Thorton","company":"Test Group","address":"10850 Test #325
","city":"Test City","state_province":"CA","postal_code":"95670","country":"USA","email_address":"[email protected]","phone_number":"999-888-3333","equipment_description":"I'm a big red truck

RSN# 0000","response_desired":"week","response_method":"email"}

I'm trying to parse the dictionary, so the resulting Dataframe contains a new column for each key and the row is populated with the resulting values for each column, like this:

//Before

1  2  3  4  5
a  b  c  d  {6:y, 7:v}

//After

1  2  3  4  5           6  7
a  b  c  d  {6:y, 7:v}  y  v

Suggestions much appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

consider df

df = pd.DataFrame([
        ['a', 'b', 'c', 'd', dict(F='y', G='v')],
        ['a', 'b', 'c', 'd', dict(F='y', G='v')],
    ], columns=list('ABCDE'))

df

   A  B  C  D                     E
0  a  b  c  d  {'F': 'y', 'G': 'v'}
1  a  b  c  d  {'F': 'y', 'G': 'v'}

Option 1
Use pd.Series.apply, assign new columns in place

df.E.apply(pd.Series)

   F  G
0  y  v
1  y  v

Assign it like this

df[['F', 'G']] = df.E.apply(pd.Series)
df.drop('E', axis=1)

   A  B  C  D  F  G
0  a  b  c  d  y  v
1  a  b  c  d  y  v

Option 2
Pipeline the whole thing using the pd.DataFrame.assign method

df.drop('E', 1).assign(**pd.DataFrame(df.E.values.tolist()))

   A  B  C  D  F  G
0  a  b  c  d  y  v
1  a  b  c  d  y  v

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...