python - 在 pandas 数据框和回填中将年扩展到月
问题描述
我有一个带有年份和一列字符串的数据框,我想将其扩展为包括月份(1-12)并回填与每年相关的字符串。
这是起始数据框:
Year Data
0 2016 YES
0 2017 NO
0 2018 NO
0 2019 YES
我也希望它看起来像:
Year Months Climate
0 2016 1 YES
0 2016 2 YES
0 2016 3 YES
...
0 2017 1 NO
0 2017 2 NO
0 2017 3 NO
0 2017 4 NO
解决方案
这是一种使用方法explode
:
# df is the given data in question
df.columns = ['year','flag']
# add a list for months 1-12
df['month'] = [list(range(1, 13)) for _ in range(df.shape[0])]
# convert list into rows
df = df.explode('month').reset_index(drop=True)
推荐阅读
- java - jdbcConnection 是否有 ExceptionListener 支持,类似于 jmsConnection?
- html - 将革命 HTML 滑块导入到 wordpress
- android - RecyclerView 将数据库条目显示为空字符串
- c# - 如何调用 DialogExtensions.RunAsync
- solr - 为什么 Solr numFound 计数与 facet_counts 不同
- coldfusion - Coldfusion 2018 不适用于 IIS 中的 htm 等其他扩展
- c++ - 有没有办法创建一个不改变程序中参数的函数
- selenium - 使用 Pytest 并行运行测试时如何使工作魅力?
- php - 对于循环和 MYSQL 乘以 $i var 上的变量值
- android - 如何关闭底部应用栏的导航抽屉