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?
read_json. Convert a JSON string to pandas object. Any valid string path is acceptable.
The get_loc() function is used to find the index of any column in the Python pandas dataframe. We simply pass the column name to get_loc() function to find index.
The iloc() function in python is one of the functions defined in the Pandas module that helps us to select a specific row or column from the data set. Using the iloc() function in python, we can easily retrieve any particular value from a row or column using index values.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With