6

I'm reading a single JSON line from file data.json with this content:

[
  {
    "timestamp": 1436266865,
    "rates": {
      "EUR": 0.911228,
      "JPY": 122.5463,
      "AUD": 1.346118
    }
  },
  {
    "timestamp": 1436277661,
    "rates": {
      "JPY": 122.4789,
      "AUD": 1.348871,
      "EUR": 0.91433
    }
  }
]

into a pandas DataFrame. I want to use the "timestamp" as the DataFrame's index. I achieve this by:

df = pandas.read_json('data.json')
df.index = df['timestamp']
df.drop('timestamp', axis=1, inplace=1)

Is it possible to do it in just one line?

1 Answer 1

11
import pandas as pd

df = pd.read_json('data.json')
df.set_index('timestamp',inplace=True)
print(df)

What this will do is set timestamp to your index. inplace=True will prevent you having to do df=df.set_index('timestamp') and by default it'll drop the column.

                                                        rates
timestamp                                                    
1436266865  {'EUR': 0.9112279999999999, 'JPY': 122.5463, '...
1436277661  {'JPY': 122.4789, 'AUD': 1.348871, 'EUR': 0.91...
Sign up to request clarification or add additional context in comments.

3 Comments

What one-line are you referring to?
Why this one-liner wouldn't work? df = pd.read_json('data.json').set_index('timestamp', inplace=True)
Because the dataframe has not been set yet, so you can't call .set_index on it unless it has been executed in memory. The code is being done from left to right after it's been read from right to left. So calling on .set_index for an undefined DF will result in None. Does that clarify things?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.