【问题标题】:Merging dataframes, based on range根据范围合并数据框
【发布时间】:2021-08-26 16:13:02
【问题描述】:

我整天都在为合并两个数据集而苦苦挣扎。一个数据集显示客户 ID、付款日期和产品代码,另一个数据集告诉我公司在特殊时期与客户达成的特殊交易。

  • 客户 = 客户
  • product_code = product_code
  • date_from

我尝试了以下脚本(python):

nef_df = pd.merge(df1, df2[['Customer', 'Product_code', 'date_from', 'date_untill']], on=['Customer', 'Product_code'])

example tables in Excell

【问题讨论】:

  • 请将您的数据发布为代码,而不是屏幕截图。另外,更新您的问题以显示您尝试过的代码。
  • 请提供足够的代码,以便其他人更好地理解或重现问题。
  • 请分享您的数据框 - 不是图片。我希望在我的示例代码上对其进行测试。

标签: python pandas merge


【解决方案1】:

根据您的示例,您需要执行外部合并

  1. 导入熊猫
import pandas as pd
  1. 创建原始数据(作为示例)
customer_1 = ['A1', 'A1', 'A2', 'A2', 'A2', 'A2', 'A3', 'A3']
paydate = ['1-6-2020', '26-11-2020', '7-1-2020', '5-12-2020', '1-3-2020', '16-7-2020', '10-1-2020', '31-12-2020']
product_code = [9100, 9100, 9100, 9100, 9200, 9200, 9400, 9400]

df1 = pd.DataFrame(
    {
        'customer':customer, 
        'paydate':paydate, 
        'product_code':product_code
    }
)
customer_2 = ['A1', 'A2', 'A2', 'A2', 'A2', 'A3', 'A3', 'A4']
product_code = [9100, 9100, 9100, 9200, 9200, 9400, 9400, 9300]
price = [27, 20, 23, 23, 22, 20, 23, 44]

df2 = pd.DataFrame(
    {
        'customer':customer_2, 
        'product_code':product_code, 
        'price':price
    }
)
  1. 执行外部合并
pd.merge(df1, df2, how='outer', on=['customer', 'product_code'])

结果表:

【讨论】:

    猜你喜欢
    • 2015-09-28
    • 2018-11-14
    • 2021-04-01
    • 2015-12-28
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    • 2016-12-27
    • 1970-01-01
    相关资源
    最近更新 更多