Pandas 按选定日期分组
我有一个与此数据框非常相似的数据框:
索引 | 日期 | 月份 |
---|---|---|
0 | 2019-12-1 | 12 |
1 | 2020-03-1 | 3 |
2 | 2020-07-1 | 7 |
3 | 2021-02-1 | 2 |
4 | 2021-09-1 | 9 |
我想合并最接近一组月份的所有日期。月份需要像这样标准化:
月份 | 标准化月份 |
---|---|
3, 4, 5 | 4 |
6, 7, 8, 9 | 8 |
1, 2, 10, 11, 12 | 12 |
因此输出将是:
索引 | 日期 | 月份 |
---|---|---|
0 | 2019-12- 1 | 12 |
1 | 2020-04-1 | 4 |
2 | 2020-08-1 | 8 |
3 | 2020-12-1 | 12 |
4 | 2021-08-1 | 8 |
I have a dataframe that is very similar to this dataframe:
index | date | month |
---|---|---|
0 | 2019-12-1 | 12 |
1 | 2020-03-1 | 3 |
2 | 2020-07-1 | 7 |
3 | 2021-02-1 | 2 |
4 | 2021-09-1 | 9 |
And i want to combine all dates that are closest to a set of months. The months need to be normalized like this:
Months | Normalized month |
---|---|
3, 4, 5 | 4 |
6, 7, 8, 9 | 8 |
1, 2, 10, 11, 12 | 12 |
So the output will be:
index | date | month |
---|---|---|
0 | 2019-12-1 | 12 |
1 | 2020-04-1 | 4 |
2 | 2020-08-1 | 8 |
3 | 2020-12-1 | 12 |
4 | 2021-08-1 | 8 |
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以迭代 DataFrame 并使用替换来更改日期。
You can iterate through the DataFrame and use replace to change the dates.
您可以尝试创建月份字典,其中:
norm_month_dict = {3: 4, 4: 4, 5: 4, 6: 8, 7: 8, 8: 8, 9: 8, 1: 12, 2: 12, 10: 12, 11: 12, 12: 12}
然后使用此字典将月份值映射到各自的标准化月份价值观。
df['normalized_months'] = df.months.map(norm_month_dict)
you can try creating a dictionary of months where:
norm_month_dict = {3: 4, 4: 4, 5: 4, 6: 8, 7: 8, 8: 8, 9: 8, 1: 12, 2: 12, 10: 12, 11: 12, 12: 12}
then use this dictionary to map month values to their respective normalized month values.
df['normalized_months'] = df.months.map(norm_month_dict)
您需要从第二个数据帧构造一个字典(假设
df1
和df2
):然后
映射
值:输出:
You need to construct a dictionary from the second dataframe (assuming
df1
anddf2
):Then
map
the values:output: