如何根据字典和另一列之间的匹配项创建新的df列

时间:2019-07-24 12:06:39

标签: python python-3.x pandas list dictionary

我有2张桌子:

表1

                          code_count
Year    Month Day   Hour    
2018    10    15    23    {'UNI017SOLC': 138}
              14    23    {'UNI017SOLC': 98}
2017     6    15    10    {'ENE001SOLC': 71}
                    13    {'ENE001SOLC': 68}
                     9    {'ENE001SOLC': 64}
2018    10    14    22    {'UNI017SOLC': 62}
              16     0    {'UNI017SOLC': 51, 'OCU039SOLC': 3}
              19     9    {'UNI017SOLC': 49, 'TRA008AUTO': 4}
2017    6     15    12    {'ENE001SOLC': 45}
2018    10    16     9    {'UNI017SOLC': 35}

表2

    ID mod                    mod_name  
0   UNI017SOLC                name 4    
1   ENT003INSC                name 54   
2   ENT003OGOV                name 52   
3   OPO021SOLC               name 253   
4   JUS007SOLC               name 116   
5   MOS001SOLC                name 30   
6   UNI016SOLC                name  3   
7   BOM002SOLC                name 27   
8   FAM006                    name  1   
9   AQU001SOLC                name 80   

如果表1的mod_name列上的键与表1的code_count值相匹配,我需要做的是创建一个具有ID mod列值的新列。表2。此列还应包含一个列表,其中mod_names对应于两个表中每个code_count键的匹配对和ID mod值。

预期输出应该是这样的:

                                   code_count
    Year    Month Day   Hour                                        new_col
    2018    10    15    23    {'UNI017SOLC': 138}                   [name 4]
                  14    23    {'UNI017SOLC': 98}                    [name 4]
    2017     6    15    10    {'ENT003INSC': 71}                    [name 54]
                        13    {'ENT003INSC': 68}                    [name 54]
                         9    {'ENT003INSC': 64}                    [name 54]
    2018    10    14    22    {'UNI017SOLC': 62}                    [name 4]
                  16     0    {'UNI017SOLC': 51, 'BOM002SOLC': 3}   [name 4, name 27]
                  19     9    {'UNI017SOLC': 49, 'JUS007SOLC': 4}   [name 4, name 116] 
    2017    6     15    12    {'ENT003OGOV': 45}                    [name 52
    2018    10    16     9    {'UNI017SOLC': 35}                    [name 4]

我该怎么做?任何帮助都感激不尽。随时问任何问题

非常感谢您!

1 个答案:

答案 0 :(得分:1)

您可以将today.getDate()转换为table 2,然后通过dictSeries.apply与lambda函数一起使用:

dict.get

[出]

d = df2.set_index('ID mod')['mod_name'].to_dict()

df['new_col'] = df.code_count.apply(lambda x: [d.get(k) for k in x.keys()])