pandas将数据从索引表添加到dataframe

时间:2017-09-18 18:04:11

标签: python pandas dataframe

我有一只大熊猫dataframe monthlyTempDiff,内容为:

monthlyAdder.ix[1:3]
         City1     City2    City3
monthID                              
1        0.01      0.1      0.02
2        0.04      0.2      0.03
8        0.17      0.3      0.05

monthID也是索引。

我有另一张表fwdTempTable

fwdTempTable.ix[1:3]
             City1     City2    City3      City4        monthID
DateTime                                                   
2017-1-01    22        24       26         16           1
2017-8-01    23        25       27         17           8
2017-2-01    13        15       17         27           2

我想根据fwdTempTablemonthlyAdder的组合添加monthID来自City1, City2, City3的数据,以获得以下内容:

fwdTempTable.ix[1:3]
             City1     City2    City3      City4        monthID
DateTime                                                   
2017-1-01    22.01     24.1     26.02      16           1
2017-8-01    23.17     25.3     27.05      17           8
2017-2-01    13.04     15.2     17.03      27           2

即。对于每一行数据框fwdTempTable,我提取City1, City2 or City3类别,并将其与monthID一起映射到数据框monthlyAdder。映射到monthlyAdder后,我将获得一个城市和一个月的正确加法器。我使用此月的加法器调整fwdTempTable中的城市数据。

这些数据框很大,我无法超越fwdTempTable的每一列的循环。

3 个答案:

答案 0 :(得分:2)

让我们试试set_indexadd

fwdTempTable.set_index('monthID', append=True).add(monthlyAdder, fill_value=0).reset_index('monthID')

输出:

           monthID  City1  City2  City3  City4
DateTime                                      
2017-1-01        1  22.01   24.1  26.02   16.0
2017-8-01        8  23.17   25.3  27.05   17.0
2017-2-01        2  13.04   15.2  17.03   27.0

答案 1 :(得分:2)

df1.reset_index().set_index('monthID')
cdx=df1.columns.isin(df.columns)    
df1.loc[:,cdx]=df1.loc[:,cdx].apply(lambda x:df.loc[x.index,x.name]+x )
df1.reset_index().set_index('DateTime')

Out[215]: 
           monthID  City1  City2  City3  City4
DateTime                                      
2017-1-01        1  22.01   24.1  26.02     16
2017-8-01        8  23.17   25.3  27.05     17
2017-2-01        2  13.04   15.2  17.03     27

答案 2 :(得分:1)

fwdTempTable.add(
    fwdTempTable[['monthID']].join(monthlyAdder, on='monthID'), fill_value=0)

           City1  City2  City3  City4  monthID
DateTime                                      
2017-1-01  22.01   24.1  26.02   16.0        2
2017-8-01  23.17   25.3  27.05   17.0       16
2017-2-01  13.04   15.2  17.03   27.0        4