0

I am trying to assign a value to a cell dataframe in python. I create a new column called RepEvnumb in my dataframe dd . I don't know what I am doing wrong because the value of the cell didn't change. I am getting this message error : "ValueError: cannot set using a multi-index selection indexer with a different length than the value" I hope someone can help me. Thank you

dd['RepEvnumb'] =''
dd['RepEvnumb'] = dd['RepEvnumb'].astype('object')
b=[{'group_id': 'E1', 'subjects_affected': '0', 'subjects_at_risk': '104'},
 {'group_id': 'E2', 'subjects_affected': '0', 'subjects_at_risk': '105'}]
dd.iloc[0,'RepEvnumb']=[dic['subjects_affected'] for dic in b]
Samir
  • 15
  • 6
  • Can you give a minimal example input and the expected output? – kmkurn Dec 06 '22 at 03:41
  • Duplicate of: https://stackoverflow.com/questions/13842088/set-value-for-particular-cell-in-pandas-dataframe-using-index – Al.Sal Dec 06 '22 at 03:55
  • @Al.Sal I applied exactly the method proposed in the link (you indicate) I got the same error message – Samir Dec 06 '22 at 04:25
  • @Samir I believe you need the column index, rather than the name. Try: `dd.at[0,'RepEvnumb'] = ...` – Al.Sal Dec 06 '22 at 06:20
  • Additionally, you are trying to set a single cell value with a list. You will need to play around with the various cell set commands - right now it's interpreting your setting the value at that cell as a multidimensional object. – Al.Sal Dec 06 '22 at 06:22
  • using `at` should resolve this – Al.Sal Dec 06 '22 at 06:23
  • @Al.Sal I have also tried with ''at'' instead of ''iloc" and also replace the column name with the column index. I keep getting the same message error : ValueError: cannot set using a multi-index selection indexer with a different length than the value – Samir Dec 06 '22 at 18:12

1 Answers1

0

My code is not working because I want to assign a list ( not a value or not a string). So this is what I did:

dd["RepEvnumb"][0] = list()
b = [
    {"group_id": "E1", "subjects_affected": "0", "subjects_at_risk": "104"},
    {"group_id": "E2", "subjects_affected": "0", "subjects_at_risk": "105"},
]
c = [dic["subjects_affected"] for dic in b]
for k in range(len(c)):
    dd["RepEvnumb"][0].append(c[k])

Thank you for your help

Aidis
  • 1,272
  • 4
  • 14
  • 31
Samir
  • 15
  • 6