Slavisha84
Slavisha84

Reputation: 767

How to extract value from dictionary into new colum?

I have a dataframe that contains one column with format like {"orderNum":123456} Here is the example:

ActionTime           Details            OrderNumber
0   1/2/2021 17:21  {"orderNum":123456} 
1   1/2/2021 20:16  {"orderNum":467899} 
2   1/3/2021 8:38   {"orderNum":753951} 

And here is what i have tried:

    df['OrderNumber'] = df[['Details','"orderNum"']].apply(lambda col: 
    col.explode()).reset_index(drop=True)
    df.head()

All what i need to is extract the order number from Details and put it into OrderNumber column. How do i do this?

Upvotes: 0

Views: 19

Answers (1)

Jan Wilamowski
Jan Wilamowski

Reputation: 3599

If the Details column is a string representation of a dictionary, you could use regular expressions to extract the number:

df = pd.DataFrame({"Action": [0, 1, 2], "Details": ['{"orderNum":123456}', '{"orderNum":467899}', '{"orderNum":753951}']})

df['OrderNumber'] = df['Details'].str.extract(r'(\d+)').astype(int)

gives

   Action              Details  OrderNumber
0       0  {"orderNum":123456}       123456
1       1  {"orderNum":467899}       467899
2       2  {"orderNum":753951}       753951

Upvotes: 1

Related Questions