【问题标题】:Format github json data into a pandas dataframe with daily dates将 github json 数据格式化为带有每日日期的 pandas 数据框
【发布时间】:2019-05-31 01:29:34
【问题描述】:

我正在尝试从 Github 检索以太坊 repo 的提交并将其格式化为具有每日日期(索引)的 DataFrame 并计为列。

我环顾四周,但我从 Github 获得的 JSON 数据对我来说很奇怪,并且不确定如何处理它。

Github JSON 数据:

      days                  total   week
0   [0, 2, 1, 2, 2, 3, 2]   12      1515283200
1   [0, 3, 2, 0, 0, 0, 0]   5       1515888000
2   [0, 2, 6, 1, 1, 5, 0]   15      1516492800

代码

#Get github data
with urllib.request.urlopen('https://api.github.com/repos/ethereum/go-ethereum/stats/commit_activity') as url:
   jStr = url.read()
#Format data
data = json.loads(jStr)
data_activity = json_normalize(data)

我希望达到:

               ETH commits   
2017-11-26     2
2017-11-27     3
...

【问题讨论】:

    标签: json python-3.x pandas


    【解决方案1】:

    我实现了一个日期生成器来简化它。

    但是,我认为创建 df 可以改进,因为我对 pandas DataFrame 不太熟悉。

    from datetime import timedelta, date, datetime
    import pandas as pd
    
    
    def date_generator(first_date):
        """ given first date returns generator which yields given date and next days as date """
        yield first_date
        while True:
            first_date += timedelta(days=1)
            yield first_date
    
    
    day_wise_commit_count = dict()
    for week_index, week in enumerate(data):
        # print('Week ', week_index)
        f_date = datetime.utcfromtimestamp(int(week['week']))  # first date of week
        date_gen = date_generator(f_date)
        # If you are sure that list is in order you can keep above two lines out of loop
        # just use first object for first date
        for day_index, commit_count in enumerate(week["days"]):
            # print('WeekDay ', week_index, day_index)
            commit_date = next(date_gen)
            day_wise_commit_count[commit_date] = commit_count
    
    df = pd.DataFrame(index=day_wise_commit_count.keys(), columns=['commit_count'])
    for d, cc in day_wise_commit_count.items():
        df.ix[d]['commit_count'] = cc
    
    print(df)
    

    【讨论】:

      【解决方案2】:

      更改 json_normalize 以将列表展平为新列,将其转换为 DatetimeIndex 并添加 timedeltas 以模除以 7 以添加天数:

      >>> data_activity = (json_normalize(data, 'days','week')
      ...                    .set_index('week').rename(columns={0:'ETH commits'}))
      >>> data_activity.index = (pd.to_datetime(data_activity.index, unit='s') + 
      ...                        pd.to_timedelta(np.arange(len(data_activity.index)) % 7, unit='d'))
      >>> print (data_activity.head(10))
      
                  ETH commits
      2018-01-07            0
      2018-01-08            2
      2018-01-09            1
      2018-01-10            2
      2018-01-11            2
      2018-01-12            3
      2018-01-13            2
      2018-01-14            0
      2018-01-15            3
      2018-01-16            2
      

      【讨论】:

      • @wizzwizz4 - 谢谢。
      【解决方案3】:

      这里,week 是每周开始的 Unix 时间。我不知道如何解释这一点,但我 70% 确信这段代码会给你你想要的格式:

      import datetime
      
      def github_norm(d):
          for week_n in range(len(d)):  # usually 52, but not guaranteed(?)
              week = d[week_n]
              week_timestamp = datetime.datetime.fromtimestamp(week["week"])
              for day_n, commits in enumerate(week["days"]):
                  yield week_timestamp + datetime.timedelta(days=day_n), commits
      

      【讨论】:

        猜你喜欢
        • 2020-09-20
        • 2021-04-11
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        • 2019-12-05
        • 2019-12-11
        • 2018-11-12
        相关资源
        最近更新 更多