为了账号安全,请及时绑定邮箱和手机立即绑定

如何合并这两个数据集?

如何合并这两个数据集?

繁花如伊 2022-06-22 22:09:42
我有两个数据集。我想使用索引进行合并。第一个数据集:index       A   B   C01/01/2010  15  20  3015/01/2010  12  15  2517/02/2010  14  13  3519/02/2010  11  10  222nt 数据集:index  year  month     price0      2010  january   701      2010  february  80我希望他们像这样加入:index       A   B   C   price01/01/2010  15  20  30  7015/01/2010  12  15  25  7017/02/2010  14  13  35  8019/02/2010  11  10  22  80问题是如何使用两列(year以及month第二个数据集)来创建临时 datetime index。
查看完整描述

2 回答

?
阿晨1998

TA贡献2037条经验 获得超6个赞

试试这个,通过从中提取.month_name()和 year( .dt.year)df1并将其与df2


>>> df1      

        index   A   B   C

0  01/01/2010  15  20  30

1  15/01/2010  12  15  25

2  17/02/2010  14  13  35

3  19/02/2010  11  10  22

>>> df2              

   index  year     month  price

0      0  2010   january     70

1      1  2010  february     80


# merging df1 and df2 by month and year.

>>> df1.merge(df2,

              left_on = [pd.to_datetime(df1['index']).dt.year,

                 pd.to_datetime(df1['index']).dt.month_name().str.lower()],

              right_on = ['year', 'month'])

输出:


      index_x   A   B   C  index_y  year     month  price

0  01/01/2010  15  20  30        0  2010   january     70

1  15/01/2010  12  15  25        0  2010   january     70

2  17/02/2010  14  13  35        1  2010  february     80

3  19/02/2010  11  10  22        1  2010  february     80


查看完整回答
反对 回复 2022-06-22
?
九州编程

TA贡献1785条经验 获得超4个赞

这是愚蠢的答案!我相信你可以做得比这更聪明:) 但考虑到你的表是一个字典列表(你可以轻松地将你的 SQL 表转换为这种格式),这很有效。我知道这不是一个干净的解决方案,但是您要求一个简单的解决方案,这可能是最容易理解的:)


months = {'january': "01",

          'february': "02",

          'march': "03",

          'april':"04",

          'may': "05",

          'june': "06",

          'july': "07",

          'august': "08",

          'september': "09",

          'october': "10",

          'november': "11",

          'december': "12"}


table1 = [{'index': '01/01/2010', 'A': 15, 'B': 20, 'C': 30},

          {'index': '15/01/2010', 'A': 12, 'B': 15, 'C': 25},

          {'index': '17/02/2010', 'A': 14, 'B': 13, 'C': 35},

          {'index': '19/02/2010', 'A': 11, 'B': 10, 'C': 22}]


table2 = [{'index': 0, 'year': 2010, 'month': 'january', 'price':70},

          {'index': 1, 'year': 2010, 'month': 'february', 'price':80}]


def joiner(table1, table2):

    for row in table2:

        row['tempDate'] = "{0}/{1}".format(months[row['month']], str(row['year']))

    for row in table1:

        row['tempDate'] = row['index'][3:]


    table3 = []

    for row1 in table1:

        row3 = row1.copy()

        for row2 in table2:

            if row2['tempDate'] == row1['tempDate']:

                row3['price'] = row2['price']

                break

        table3.append(row3)

    return(table3)


table3 = joiner(table1, table2)

print(table3)


查看完整回答
反对 回复 2022-06-22
  • 2 回答
  • 0 关注
  • 167 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号