Разделите JSON файл на разные временные интервалы с помощью Python - PullRequest
0 голосов
/ 05 мая 2020

В текущем исследовательском проекте я пытаюсь разбить файл JSON на разные временные интервалы. На основе объекта «Дата» я хочу проанализировать содержимое файла JSON по кварталам, то есть с 01 января по 31 марта, с 01 апреля по 20 июня и т. Д. c.

В идеале код должен был бы выбрать самую старую дату в файле и добавить к ней квартальные вставки времени. Я провел исследование по этому поводу, но пока не нашел никаких полезных методов.

Есть ли какой-нибудь разумный способ включить это в код? Файл JSON имеет следующую структуру:

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

И существующий соответствующий фрагмент кода выглядит следующим образом:

import pandas as pd

file = pd.read_json (r'Glassdoor_A.json')
data = json.load(file)

# Create an empty dictionary
d = dict()

# processing:
for row in data:
    line = row['Text Main']
    # Remove the leading spaces and newline character
    line = line.strip()

    # Convert the characters in line to
    # lowercase to avoid case mismatch
    line = line.lower()

    # Remove the punctuation marks from the line
    line = line.translate(line.maketrans("", "", string.punctuation))

    # Split the line into time intervals
    line.sort_values(by=['Date'])
    line.tshift(d, int = 90, freq=timedelta, axis='Date')

    # Split the line into words
    words = line.split(" ")

    # Iterate over each word in line
    for word in words:
        # Check if the word is already in dictionary
        if word in d:
            # Increment count of word by 1
            d[word] = d[word] + 1
        else:
            # Add the word to dictionary with count 1
            d[word] = 1

# Print the contents of dictionary
for key in list(d.keys()):
    print(key, ":", d[key])

    # Count the total number of words
    total = sum(d.values())
    print(d[key], total)

1 Ответ

0 голосов
/ 12 мая 2020

Ниже вы можете найти ответ на свой вопрос. Данные могут быть разрезаны с помощью Pandas, назначив дату начала и дату окончания и сравнив объект JSON Date с этими датами.

Важное примечание: данные должны быть нормализованы, а даты должны быть перед обработкой информации конвертируется в формат Pandas datetime.

import string
import json
import csv

import pandas as pd
import datetime

import numpy as np


# Loading and reading dataset
file = open("Glassdoor_A.json", "r")
data = json.load(file)
df = pd.json_normalize(data)
df['Date'] = pd.to_datetime(df['Date'])


# Create an empty dictionary
d = dict()


# Filtering by date
start_date = "01/01/2018"
end_date = "31/03/2018"

after_start_date = df["Date"] >= start_date
before_end_date = df["Date"] <= end_date

between_two_dates = after_start_date & before_end_date
filtered_dates = df.loc[between_two_dates]

print(filtered_dates)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...