我正在开发一个Python解决方案来应对数据转换挑战,但遇到了一个我似乎无法解决的小障碍.I want to merge the two data frames (i.e., df1 & df2) to create a new data frame that has inserted df2['value2'] into df1['value1'] while considering date and 'Type' alignment.有人解决过类似的问题吗?Pandas 是解决这个问题的最佳图书馆吗?

请参阅下面我在jupyter笔记本中用于解决方案测试的代码片段.

import pandas as pd 

df1 = pd.DataFrame({ 'Type': ['Labor', 'Material', 'Labor', 'Material' , 'Labor', 'Material', 'Labor', 'Material'],'date1': ['2021-01-01', '2021-01-01', '2021-02-01', '2021-02-01', '2021-03-01', '2021-03-01', '2021-04-01', '2021-04-01'], 'value1': [0,0,0,0,0,0,0,0]})
df2 = pd.DataFrame({ 'Type': ['Labor', 'Material', 'Labor', 'Material'],'date2': ['2021-01- 
11', '2021-02-22', '2021-02-05', '2021-03-15'], 'value2': [10,20,25,45]})

display(df1)
display(df2)

df1['date1'] = pd.to_datetime(df1['date1'])
df2['date2'] = pd.to_datetime(df2['date2'])

df1 = df1.sort_values(['date1', 'Type'])
df2 = df2.sort_values(['date2', 'Type'])

merge_df = pd.merge_asof(df2, df1, left_on= 'date2', right_on= 'date1' , by = 'Type', 
direction = 'nearest')

display(merge_df)

我试图实现的输出如下所示.

Type Date Value
Labor 2021-01-01 10
Material 2021-01-01 0
Labor 2021-02-01 25
Material 2021-02-01 20
Labor 2021-03-01 0
Material 2021-03-01 45
Labor 2021-04-01 0
Material 2021-04-01 0

推荐答案

merge_asof是左合并,您需要在左侧使用df1.您还必须将月份用作by:

out = (pd.merge_asof(df1.assign(month=df1['date1'].dt.to_period('M')),
                     df2.assign(month=df2['date2'].dt.to_period('M')),
                     left_on='date1', right_on='date2',
                     by=['Type', 'month'], direction='nearest')
         .fillna({'value2': 0})
      )

输出:

       Type      date1  value1    month      date2  value2
0     Labor 2021-01-01       0  2021-01 2021-01-11    10.0
1  Material 2021-01-01       0  2021-01        NaT     0.0
2     Labor 2021-02-01       0  2021-02 2021-02-05    25.0
3  Material 2021-02-01       0  2021-02 2021-02-22    20.0
4     Labor 2021-03-01       0  2021-03        NaT     0.0
5  Material 2021-03-01       0  2021-03 2021-03-15    45.0
6     Labor 2021-04-01       0  2021-04        NaT     0.0
7  Material 2021-04-01       0  2021-04        NaT     0.0

中间体:

# df1.assign(month=df1['date1'].dt.to_period('M'))
       Type      date1  value1    month
0     Labor 2021-01-01       0  2021-01
1  Material 2021-01-01       0  2021-01
2     Labor 2021-02-01       0  2021-02
3  Material 2021-02-01       0  2021-02
4     Labor 2021-03-01       0  2021-03
5  Material 2021-03-01       0  2021-03
6     Labor 2021-04-01       0  2021-04
7  Material 2021-04-01       0  2021-04

# df2.assign(month=df2['date2'].dt.to_period('M'))
       Type      date2  value2    month
0     Labor 2021-01-11      10  2021-01
2     Labor 2021-02-05      25  2021-02
1  Material 2021-02-22      20  2021-02
3  Material 2021-03-15      45  2021-03

Python相关问答推荐

如何使用Python中的clinicalTrials.gov API获取完整结果?

Python:在类对象内的字典中更改所有键的索引,而不是仅更改一个键

对某些列的总数进行民意调查,但不单独列出每列

在Google Colab中设置Llama-2出现问题-加载判断点碎片时Cell-run失败

对于一个给定的数字,找出一个整数的最小和最大可能的和

为什么符号没有按顺序添加?

在线条上绘制表面

导入...从...混乱

driver. find_element无法通过class_name找到元素'""

连接一个rabrame和另一个1d rabrame不是问题,但当使用[...]'运算符会产生不同的结果

当我try 在django中更新模型时,模型表单数据不可见

如何使用Numpy. stracards重新编写滚动和?

无论输入分辨率如何,稳定扩散管道始终输出512 * 512张图像

matplotlib + python foor loop

为什么常规操作不以其就地对应操作为基础?

如何在Gekko中使用分层条件约束

用两个字符串构建回文

浏览超过10k页获取数据,解析:欧洲搜索服务:从欧盟站点收集机会的微小刮刀&

Django在一个不是ForeignKey的字段上加入'

修改.pdb文件中的值并另存为新的