Home > Net >  Read data from a dictionary in pandas and assign new column value
Read data from a dictionary in pandas and assign new column value

Time:07-03

I have dict data in a pandas column and I am attempting to assign values to a new column from the dict.

import pandas as pd

df = pd.DataFrame({'n': [np.nan, np.nan],
                   'd': [{'status': {'version': '1.0.0'},
                          'p': [{'identifier': {'Id': 5155,
                          'fips': '07',
                          'aId': 5175},
                          'lt': {'ltnum': '14',
                          'ls1': 0.1485537,
                          'ls2': 6471,
                          'ptype': 'NO'}}]}, 
                          np.nan]
                 })

When I try:

df['n'].fillna(df['d'].str['p'][0][0]['lt']['ls1'], inplace=True)

I get a:

TypeError: 'float' object is not subscriptable

CodePudding user response:

You have to use str accessor everytime:

df['n'].fillna(df['d'].str['p'].str[0].str['lt'].str['ls1'], inplace=True)
print(df)

# Output
          n                                                  d
0  0.148554  {'status': {'version': '1.0.0'}, 'p': [{'ident...
1       NaN                                                NaN
  • Related