首页 > 解决方案 > 如何将值除以月份中的天并在 Pandas 中创建天列?

问题描述

我有一个看起来像这样的熊猫数据框:

   year  month  name  value1  value2
0  2021    7    cars   5000    4000 
1  2021    7   boats   2000     250
2  2021    9    cars   3000    7000

我希望它看起来像这样:

    year  month day  name  value1  value2
0   2021    7    1   cars  161.29  129.03
1   2021    7    2   cars  161.29  129.03
2   2021    7    3   cars  161.29  129.03
3   2021    7    4   cars  161.29  129.03
              ...
31  2021    7    1   boats  64.51   8.064
32  2021    7    2   boats  64.51   8.064
33  2021    7    3   boats  64.51   8.064
              ...
62  2021    9    1    cars   100    233.33
63  2021    9    1    cars   100    233.33
64  2021    9    1    cars   100    233.33

这个想法是我想将值列除以当月的天数,并创建一个天列,以便最后我可以实现一个连接年、月和日的日期列。

谁能帮我?

标签: pythonpandasnumpy

解决方案


一种选择是使用monthrangefromcalendar获取给定月份的天数,将该值除以该月的天数,然后用于Index.repeat扩展 DataFrame 并groupby cumcount添加天数:

from calendar import monthrange

import pandas as pd

df = pd.DataFrame(
    {'year': {0: 2021, 1: 2021, 2: 2021}, 'month': {0: 7, 1: 7, 2: 9},
     'name': {0: 'cars', 1: 'boats', 2: 'cars'},
     'value1': {0: 5000, 1: 2000, 2: 3000},
     'value2': {0: 4000, 1: 250, 2: 7000}})
days_in_month = (
    df[['year', 'month']].apply(lambda x: monthrange(*x)[1], axis=1)
)

# Calculate new values
df.loc[:, 'value1':] = df.loc[:, 'value1':].div(days_in_month, axis=0)
df = df.loc[df.index.repeat(days_in_month)]  # Scale Up DataFrame
df.insert(2, 'day', df.groupby(level=0).cumcount() + 1)  # Add Days Column
df = df.reset_index(drop=True)  # Clean up Index

df

    year  month  day  name      value1      value2
0   2021      7    1  cars  161.290323  129.032258
1   2021      7    2  cars  161.290323  129.032258
2   2021      7    3  cars  161.290323  129.032258
3   2021      7    4  cars  161.290323  129.032258
4   2021      7    5  cars  161.290323  129.032258
..   ...    ...  ...   ...         ...         ...
87  2021      9   26  cars  100.000000  233.333333
88  2021      9   27  cars  100.000000  233.333333
89  2021      9   28  cars  100.000000  233.333333
90  2021      9   29  cars  100.000000  233.333333
91  2021      9   30  cars  100.000000  233.333333

推荐阅读