python - 如何将值除以月份中的天并在 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
这个想法是我想将值列除以当月的天数,并创建一个天列,以便最后我可以实现一个连接年、月和日的日期列。
谁能帮我?
解决方案
一种选择是使用monthrange
fromcalendar
获取给定月份的天数,将该值除以该月的天数,然后用于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
推荐阅读
- c# - 从谷歌图像搜索中获取 HTML 后,在 C# 搜索的第一页上获取每个图像的 URL 的最佳方法是什么?
- vba - 在 PowerPoint 中访问任务完成状态
- javascript - Nativescript 水平滚动效果很好,但不适用于项目模板
- autodesk-forge - 将 AutoDesk Forge 查看器环境从本地切换到 AutodeskProduction
- ios - 如果用户的信息不正确,如何阻止用户通过登录页面 IOS
- python-3.x - ValueError:尝试在python中对列表进行排序时无法将列转换为布尔值
- authentication - 我的 nuxt-auth 令牌配置正确,但令牌从未存储
- c++ - 如何为 c/c++ 程序生成没有崩溃/段错误的核心转储文件
- android - ArrayList$Itr.next 抛出错误 concurrentModificationException
- python-3.x - Python:在类调用中使用另一个类的函数