【问题标题】:Loop through dates modifying column value based on month循环遍历基于月份修改列值的日期
【发布时间】:2021-05-07 19:13:45
【问题描述】:

我有两个 pandas 数据框 - 时间序列和每月平均值,如下所示

import pandas as pd

df = pd.DataFrame({'date': ['1/10/2000', '3/11/2001', '6/12/2001', '4/03/2000', '23/07/2001', '15/07/2000', '05/05/2001', '17/12/2000', '9/9/2001', '2/24/2001'],
                   'value': [2, 3, 4, 1, 4, 7, 9, 4, 5, 6]})
df['date'] = pd.to_datetime(df['date'])
df

monthly = pd.DataFrame({'month': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
                   'value_m': [0.49, 0.73, 0.88, 0.41, 0.77, 0.24, 0.40, 0.23, 0.51, 0.68, 0.17, 0.43]})
monthly

目标是遍历日期并确定月份,然后通过添加每月数据框中相应的每月值来修改 df 数据框中的值列。例如,日期的第一个值是 '1/10/2000',因此月份是 Jan (1),新值是 2 + 0.49 = 2.49。

提前致谢!

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    试试这个:

    monthly_value = monthly.set_index('month')['value_m']
    
    def get_new_value(data):
        try:
            value_m = monthly_value[data.date.month]
            return data.value + value_m
        except:
            return data.value
    
    
    df.value = df.apply(lambda x: get_new_value(x), axis=1)
    print (df)
    

    输出:

           date    value
    0   2000-01-10  2.49
    1   2001-03-11  3.88
    2   2001-06-12  4.24
    3   2000-04-03  1.41
    4   2001-07-23  4.40
    5   2000-07-15  7.40
    6   2001-05-05  9.77
    7   2000-12-17  4.43
    8   2001-09-09  5.51
    9   2001-02-24  6.73
    

    【讨论】:

    • 非常感谢您花时间回答我的问题。我衷心感谢
    【解决方案2】:

    使用Series.map by Series.dt.monthmonthly DataFrame 转换为Series 并使用month 索引并添加到​​value

    df['value'] += df['date'].dt.month.map(monthly.set_index('month')['value_m'])
    #working like
    #df['value'] = df['value'] + df['date'].dt.month.map(monthly.set_index('month')['value_m'])
    print (df)
            date  value
    0 2000-01-10   2.49
    1 2001-03-11   3.88
    2 2001-06-12   4.24
    3 2000-04-03   1.41
    4 2001-07-23   4.40
    5 2000-07-15   7.40
    6 2001-05-05   9.77
    7 2000-12-17   4.43
    8 2001-09-09   5.51
    9 2001-02-24   6.73
    

    10k 行的性能:

    df = pd.concat([df] * 1000, ignore_index=True)
    

    In [120]: %timeit df['value'] += df['date'].dt.month.map(monthly.set_index('month')['value_m'])
    2.73 ms ± 117 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    
    In [121]: %timeit df.value = df.apply(lambda x: get_new_value(x), axis=1)
    299 ms ± 5.92 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
    

    【讨论】:

      猜你喜欢
      • 2011-01-10
      • 1970-01-01
      • 1970-01-01
      • 2020-11-07
      • 1970-01-01
      • 2021-12-30
      • 2013-09-21
      • 1970-01-01
      相关资源
      最近更新 更多