【问题标题】:How to create a function to convert monthly data to daily, weekly in pandas dataframe?如何在熊猫数据框中创建将每月数据转换为每日、每周的函数?
【发布时间】:2018-10-21 21:28:37
【问题描述】:

我在数据框中有以下每月数据,我需要将数据转换为每周、每天、每两周一次。

date              chair_price     vol_chair
01-09-2018         23              30
01-10-2018         53              20

daily: price as same and vol_chair divided by days of the month
weekly: price as same and vol_chair divided by number of weeks in a month

预期输出: 每日:

   date              chair_price     vol_chair
01-09-2018            23               1
02-09-2018            23               1
03-09-2018            23               1
..
30-09-2018            23               1
01-10-2018            53               0.64
..
31-10-2018            53               0.64

每周:

     date              chair_price     vol_chair
02-09-2018               23              6
09-09-2018               23              6 
16-09-2018               23              6   
23-09-2018               23              6 
30-09-2018               23              6
07-10-2018               53              5
14-10-2018               53              5
..

我使用下面的代码作为 vol 列,任何快速的方法一起做,即保持价格不变和 vol - 采取行动并找出一个月中的周数

df.resample('W').ffill().agg(lambda x: x/4)
df.resample('D').ffill().agg(lambda x: x/30)
and need to use calendar.monthrange(2012,1)[1] to identify days 
def func_count_number_of_weeks(df):
    return len(calendar.monthcalendar(df['DateRange'].year, df['DateRange'].month))

def func_convert_from_monthly(df, col, category, columns):
    if category == "Daily":
        df['number_of_days'] = df['DateRange'].dt.daysinmonth
        for column in columns:
            df[column] = df[column] / df['number_of_days'] 
        df.drop('number_of_days', axis=1, inplace=True)
    elif category == "Weekly":
        df['number_of_weeks'] = df.apply(func_count_number_of_weeks, axis=1)
        for column in columns:
            df[column] = df[column] / df['number_of_weeks'] 
        df.drop('number_of_weeks', axis=1, inplace=True)

    return df

def func_resample_from_monthly(df,col, category):
    df.set_index(col, inplace=True)
    df.index = pd.to_datetime(df.index, dayfirst=True)
    if category == "Monthly":
        df = df.resample('MS').ffill()
    elif category == "Weekly":
        df = df.resample('W').ffill()

    return df

【问题讨论】:

  • 您至少可以尝试一些事情来表明您有兴趣解决您的问题吗?一旦你的前一个解决了,你就问另一个。 Stack Overflow 不是免费劳动力。你应该展示你的努力。
  • 不好意思,急着提了

标签: pandas


【解决方案1】:

用途:

#convert to datetimeindex
df.index = pd.to_datetime(df.index, dayfirst=True)

#add new next month for correct resample
idx = df.index[-1] + pd.offsets.MonthBegin(1)

df = df.append(df.iloc[[-1]].rename({df.index[-1]: idx}))

#resample with forward filling values, remove last helper row
#df1 = df.resample('D').ffill().iloc[:-1]
df1 = df.resample('W').ffill().iloc[:-1]

#divide by size of months
df1['vol_chair'] /= df1.resample('MS')['vol_chair'].transform('size')
print (df1)

            chair_price  vol_chair
date                              
2018-09-02           23        6.0
2018-09-09           23        6.0
2018-09-16           23        6.0
2018-09-23           23        6.0
2018-09-30           23        6.0
2018-10-07           53        5.0
2018-10-14           53        5.0
2018-10-21           53        5.0
2018-10-28           53        5.0

【讨论】:

  • 嗨,jezrael,感谢您的回复!如果您可以查看,我也编写了类似的代码。另外,为什么我们需要使用 df.resample('W').ffill().iloc[:-1] 来做 iloc?
  • @user3222101 - 因为最后一行是November,所以只有在十月的所有日子里都需要填写。可以忽略它并检查输出中的最后一行。
  • 这与我试图解决的问题非常相似。假设一个星期在两个月之间重叠,这段代码将如何处理它?它会根据每个月的天数在它们之间进行划分吗?
  • @vevekseetharaman - 没有数据不容易说,最好是使用示例数据、预期输出和您尝试的内容创建新问题(在此处免费添加此解决方案)
  • 当然@jezrael,将创建一个新问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-02
  • 1970-01-01
  • 1970-01-01
  • 2022-06-30
  • 2015-03-23
  • 2020-07-06
相关资源
最近更新 更多