【问题标题】:Create a dictionary from two pandas series split by a delimiter从由分隔符分割的两个熊猫系列创建字典
【发布时间】:2021-03-26 12:05:30
【问题描述】:

如果用“:”分割,我有两列 A 和 B 具有相应的键和值。我正在尝试在 ColumnC 中创建一个字典,以便以后能够根据 ColumnC 中的键添加更多列。

ColumnA ColumnB ColumnC abc def
abc:def:ghi 111:222:333 {'abc':111,'def':222,'ghi':333} 111 222
jkl:def 444:555 {'jkl':444,'def':555} 555
abc:stu:vwx:ach 666:777:888:999 {'abc':666,'stu':777,'vwx':888,'ach':999} 666

当列表不是熊猫系列的一部分时,下面的代码有效,但是当我应用于熊猫系列时,它会抛出 TypeError: unhashable type: 'list'。

ColumnA = 'abc:def:ghi'
ColumnB = '111:222:333'

ColumnA_list = ColumnA.split(':')
ColumnB_list = ColumnB.split(':')

ColumnC = dict(zip(ColumnA_list, ColumnB_list))
print(ColumnC)

但是,下面的代码会抛出错误:

KEYS = df['ColumnA'].str.split(':')
VALUES = df['ColumnB'].str.split(':')

df['ColumnC'] = dict(zip(KEYS, VALUES))
print(df['ColumnC'])

TypeError: unhashable type: 'list'

我尝试使用其他方法创建字典,但无法克服此错误。我还尝试先将它们转换为元组和集合,但没有奏效。这是实现我尝试从 ColumnC 获得的最佳方法吗?有其他方法吗?

【问题讨论】:

    标签: python pandas dictionary typeerror


    【解决方案1】:

    简化了一下流程,如下:

    代码:

    import pandas as pd
    import numpy as np
    
    ColumnA = 'abc:def:ghi'
    ColumnB = '111:222:333'
    ColumnC = dict(zip(ColumnA.split(':'), ColumnB.split(':')))
    print(ColumnA, ColumnB, ColumnC)
    
    df = pd.DataFrame()
    df['ColumnA'] = ColumnA.split(':')
    df['ColumnB'] = ColumnB.split(':')
    df['ColumnC'] = ColumnC.items()
    print(df)
    

    输出:

    abc:def:ghi 111:222:333 {'abc': '111', 'def': '222', 'ghi': '333'}
      ColumnA ColumnB     ColumnC
    0     abc     111  (abc, 111)
    1     def     222  (def, 222)
    2     ghi     333  (ghi, 333)
    

    【讨论】:

      【解决方案2】:

      你可以试试:

      >>> df
                 ColumnA          ColumnB
      0      abc:def:ghi      111:222:333
      1          jkl:def          444:555
      2  abc:stu:vwx:ach  666:777:888:999
      >>>
      >>> df['ColumnC'] = df.apply(lambda row: dict(zip(row.ColumnA.split(':'), row.ColumnB.split(':'))), axis=1)
      >>>
      >>> df['ColumnC']
      0    {'abc': '111', 'def': '222', 'ghi': '333'}              
      1    {'jkl': '444', 'def': '555'}                            
      2    {'abc': '666', 'stu': '777', 'vwx': '888', 'ach': '999'}
      Name: ColumnC, dtype: object
      

      【讨论】:

      猜你喜欢
      • 2016-09-09
      • 2021-02-06
      • 2018-02-26
      • 2019-03-01
      • 2013-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-17
      相关资源
      最近更新 更多