Davide Porzio
Davide Porzio

Reputation: 169

Dot notation in pandas/json

Can somebody explain me why I cannot access a pandas dataframe created from json with a dot notation. Or at least, not if the dataframe is not too nested.

If my json file consists of:

{
  "mass":{
    "e": 0.511,
    "mu": 105.758,
    "pi0": 134.977,
    "pi+": 139.570,
    "k0": 497.648,
    "k+": 493.667
  }
}

I can perfectly do:

glob = pd.read_json('Constants/constants.json')
print glob.mass.e

However, if my json file looks like this:

{
  "physics":{
    "mass":{
      "e": 0.511,
      "mu": 105.758,
      "pi0": 134.977,
      "pi+": 139.570,
      "k0": 497.648,
      "k+": 493.667
    },
    "ckm":{
      "ud": 0.97427,
      "us": 0.22534
    }
  },
  "experiment":{
    "detector":{
      "width": 2.56,
      "height": 2.33,
      "length": 10.37,
      "distance": 470
    },
    "decayPipe":{
      "length": 50
    }
  }
}

Then, doing:

glob = pd.read_json('Constants/constants.json')
print glob.physics.mass.e

will return

AttributeError: 'dict' object has no attribute 'e'

Upvotes: 1

Views: 561

Answers (1)

jeff carey
jeff carey

Reputation: 2373

In the first instance mass is a Series which creates properties for each of the items under it. It does not repeat this process n levels deep so in the second instance mass is just a dict which you need to use bracket notation to access.

Upvotes: 1

Related Questions