【问题标题】:Map two dataframes with different number of rows based on year month and day of their columns根据列的年月日映射具有不同行数的两个数据框
【发布时间】:2021-03-14 15:43:17
【问题描述】:

我有一个如下数据框(df1):

index,col1,col2
2020-01-01,A,Y
2020-01-02,B,Z

还有一个类似下面的(df2):

index,date, .....
1,2020-01-01 13:44
2,2020-01-01 15:22
3,2020-01-01 23:11
4,2020-01-01 13:44
5,2020-01-02 13:28
6,2020-01-02 17:55

我需要将 df2['date'] 年、月和日与 df1.index 年、月和日进行映射,以获得最终的数据框,如下所示:

index,col1,col2
2020-01-01 13:44,A,Y
2020-01-01 15:22,A,Y
2020-01-01 23:11,A,Y
2020-01-01 13:44,A,Y
2020-01-02 13:28,B,Z
2020-01-02 17:55,B,Z

类似下面的东西可以完成这项工作:

pd.Dataframe(mapped_values, index=df2['date'], columns=df1.columns)

如何在此处获取 mapped_values?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    你可以试试合并:

    df2['day'] = df2['date'].dt.normalize()
    df2.merge(df1, left_on='day', right_index=True)
    

    输出:

                         date        day col1 col2
    index                                         
    1     2020-01-01 13:44:00 2020-01-01    A    Y
    2     2020-01-01 15:22:00 2020-01-01    A    Y
    3     2020-01-01 23:11:00 2020-01-01    A    Y
    4     2020-01-01 13:44:00 2020-01-01    A    Y
    5     2020-01-02 13:28:00 2020-01-02    B    Z
    6     2020-01-02 17:55:00 2020-01-02    B    Z
    

    【讨论】:

      【解决方案2】:

      下面是这样做的。

      模块

      import pandas as pd
      import io
      

      数据

      df1 = pd.read_csv(io.StringIO("""
      index,col1,col2
      2020-01-01,A,Y
      2020-01-02,B,Z
      """), sep=",", engine="python")
      
      df2 = pd.read_csv(io.StringIO("""
      index,date
      1,2020-01-01 13:44
      2,2020-01-01 15:22
      3,2020-01-01 23:11
      4,2020-01-01 13:44
      5,2020-01-02 13:28
      6,2020-01-02 17:55
      """), sep=",", engine="python")
      

      日期格式

      df1['ndate'] = pd.to_datetime(df1['index'])
      df2['ndate'] = pd.to_datetime(df2['date'])
      df2['ndate'] = pd.to_datetime(df2['ndate'].dt.strftime('%Y-%m-%d'))
      

      合并

      pd.merge(df2, df1, on=['ndate'])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-13
        • 2021-12-07
        • 2021-10-23
        • 2017-01-16
        • 2018-08-07
        • 2021-10-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多