连接多个数据帧与大熊猫一起

问题描述 投票:0回答:2

下面我有两个数据帧不在话下。

df1 dataframe consists SaleDate column as the unique key column DF1形状(12,11)

下面的第二数据帧提

df2 dataframe consists SaleDate column as the unique key column

DF2形状是(2,19)

但每一个数据帧的尺寸是不同的。

有些我是如何根据新的[日月年]列可以从SaleDate导出并添加相同的尿素价格为各自今年整整一个月参加2个数据帧。

预计输出下面提到

df3 data-frame consist of monthly ureaprice for each raw at the data-frame新数据帧的形状(13,11)

***实际DF1由2万条记录和DF2包括360条记录。

我想加入两个数据帧与左连接得到上面的输出。但是,无法实现它。

import pandas as pd # Import Pandas for data manipulation using dataframes

    df1['month_year']=pd.to_datetime(df1['SaleDate']).dt.to_period('M')
    df2['month_year'] = pd.to_datetime(df2['SaleDate']).dt.to_period('M')

df1 = pd.DataFrame({'Factory': ['MF0322','MF0657','MF0300','MF0790'], 
               'SaleDate': ['2013-02-07','2013-03-07','2013-06-07','2013-05-07']
               'month-year':['2013-02','2013-03','2013-06','2013-05']})

df2 = pd.DataFrame({'Price': ['398.17','425.63','398.13','363','343.33','325.13'], 
                   'Month': ['2013-01-01','2013-02-01','2013-03-01','2013-04-01','2013-05-01','2013-06-01']
                   'month-year':['2013-01','2013-02','2013-03','2013-04','2013-05','2013-06']})

最终的数据帧

s1 = pd.merge(df1, df2, how='left', on=['month_year'])

关于对尿素价格的所有值是“南”。

希望在这方面得到专家的意见。

python pandas dataframe join left-join
2个回答
0
投票

假设你SaleDate列串dtypes,你可能只是做: df1['month_year'] = df1['SaleDate'].apply(lambda x: x[:7]) df2['month_year'] = df2['SaleDate'].apply(lambda x: x[:7])

我认为剩下的应该努力!


0
投票

我复制你的代码,而无需month_year列:

df1 = pd.DataFrame({'Factory': ['MF0322','MF0657','MF0300','MF0790'],
    'SaleDate': ['2013-02-07','2013-03-07','2013-06-07','2013-05-07']})
df2 = pd.DataFrame({'Price': ['398.17','425.63','398.13','363','343.33','325.13'],
    'Month': ['2013-01-01','2013-02-01','2013-03-01','2013-04-01','2013-05-01',
    '2013-06-01']})

然后,我创建了两个DataFrames month_year列:

df1['month_year'] = pd.to_datetime(df1['SaleDate']).dt.to_period('M')
df2['month_year'] = pd.to_datetime(df2['Month']).dt.to_period('M')

和它们合并:

s1 = pd.merge(df1, df2, how='left', on=['month_year'])

当我执行print(s1)我:

  Factory    SaleDate month_year   Price       Month
0  MF0322  2013-02-07    2013-02  425.63  2013-02-01
1  MF0657  2013-03-07    2013-03  398.13  2013-03-01
2  MF0300  2013-06-07    2013-06  325.13  2013-06-01
3  MF0790  2013-05-07    2013-05  343.33  2013-05-01

正如你所看到的,Price列是正确的,等于(根据Price),以SaleDate为各自的一个月。

所以一般你的代码就可以了。

检查是否存在错误的其他来源。例如。在你的代码片段:

  • 您第一次设置month_year在每个数据帧,
  • 然后你再创建两个DataFrames,破坏了以前的内容。

复制我的代码(仅此而已),并确认它给出了相同的结果。也许你的问题的根源是一些完全别的地方?

需要注意的是如您df2Month列,而不是SaleDate。也许这是根本原因?

© www.soinside.com 2019 - 2024. All rights reserved.