Malte Susen
Malte Susen

Reputation: 845

Pandas Date Conversion: TypeError: list indices must be integers or slices, not str

For a current research project, I am planning to analyse rows between two dates within a JSON file on basis of Python/Pandas. When converting the JSON Date object into the Pandas format, I am receiving the following notifcation TypeError: list indices must be integers or slices, not str with reference to the line df['Date'] = pd.to_datetime(df['Date']).

I have already checked some pages referring to the same problem but have not found a solution yet. Is there any smart tweak to get this running?

Below is a sample of the JSON file:

[
{"No":"121","Stock Symbol":"A","Date":"05/11/2017","Text Main":"Sample text"}
]

The relevant code segment looks as follows:

import pandas as pd
import datetime
import numpy as np

# Loading and reading dataset
file = open("Glassdoor_A.json", "r")
df = json.load(file)

# Create an empty dictionary
d = dict()

# Converting the Date format
df['Date'] = pd.to_datetime(df['Date'])

Upvotes: 0

Views: 859

Answers (1)

NYC Coder
NYC Coder

Reputation: 7604

Try this:

file = open("1.json", "r")
data = json.load(file)
df = pd.json_normalize(data)
df['Date'] = pd.to_datetime(df['Date'])
print(df)

    No Stock Symbol       Date    Text Main
0  121            A 2017-05-11  Sample text

Upvotes: 2

Related Questions