Home > other >  Get the dictionary from elements in the list of a column where key-value pair are number of elements
Get the dictionary from elements in the list of a column where key-value pair are number of elements

Time:12-19

I have a dataframe

df = pd.DataFrame([["X",["A","B","C","D"]],["Y",["E","F","G"]],["Z",["H","I","J","K","L"]]],columns=["type","id"])
type    id
X   [A, B, C, D]
Y   [E, F, G]
Z   [H, I, J, K, L]

I want 2 new columns id_len which tells the number of elements in the list of id column and id_dict which makes the dictionary of columns id_len and id as key-value.

Expected output

df_new = pd.DataFrame([["X",["A","B","C","D"],[1,2,3,4],{1:"A",2:"B",3:"C",4:"D"}],["Y",["E","F","G"],[1,2,3],{1:"E",2:"F",3:"G"}],["Z",["H","I","J","K","L"],[1,2,3,4,5],{1:"H",2:"I",3:"J",4:"K",5:"L"}]],columns=["type","id","id_len","id_dict"])

type    id             id_len                    id_dict
X   [A, B, C, D]     [1, 2, 3, 4]      {1: 'A', 2: 'B', 3: 'C', 4: 'D'}
Y   [E, F, G]        [1, 2, 3]         {1: 'E', 2: 'F', 3: 'G'}
Z   [H, I, J, K, L]  [1, 2, 3, 4, 5]   {1: 'H', 2: 'I', 3: 'J', 4: 'K', 5: 'L'}

How to do it?

CodePudding user response:

i hope this can help:

df.assign(id_len=df['id'].map(lambda x: list(range(1,len(x) 1))), 
          id_dict=df['id'].map(lambda x: dict(enumerate(x,1))))

>>>
'''
    type                           id            id_len                                  id_dict
0      X         ['A', 'B', 'C', 'D']      [1, 2, 3, 4]         {1: 'A', 2: 'B', 3: 'C', 4: 'D'}
1      Y              ['E', 'F', 'G']         [1, 2, 3]                 {1: 'E', 2: 'F', 3: 'G'}
2      Z    ['H', 'I', 'J', 'K', 'L']   [1, 2, 3, 4, 5] {1: 'H', 2: 'I', 3: 'J', 4: 'K', 5: 'L'}
  • Related