How to select a float value from a dataframe column which is in dictionary form in python?

  Kiến thức lập trình

I have a dataframe like this:

Date                      comp
01-01-2022      {'dfp':25.02,'ftp':12.06}
01-02-2022      {'dfp':12.01,'ftp':40.05}
01-03-2022      {'dfp':50.20,'ftp':35.25}

I am trying to create a new column which has only the dfp value from the comp column.

Expected Output:

Date                      comp                   New
01-01-2022      {'dfp':25.02,'ftp':12.06}       25.02
01-02-2022      {'dfp':12.01,'ftp':40.05}       12.01
01-03-2022      {'dfp':50.20,'ftp':35.25}       50.20

I tried the below code to execute the same:

def new_col(x):
   for i in range(len(df)):
       return x[i]['dfp']

df['New'] = df['comp'].apply(new_col)

But the above code creates error. where am i going wrong?

3

Use can use the .str accessor to get data from dictionary in pandas dataframes:

df['New'] = df['comp'].str['dfp']

Output:

         Date                          comp    New
0  01-01-2022  {'dfp': 25.02, 'ftp': 12.06}  25.02
1  01-02-2022  {'dfp': 12.01, 'ftp': 40.04}  12.01
2  01-03-2022   {'dfp': 50.2, 'ftp': 35.25}  50.20

LEAVE A COMMENT