I want to set the value of a pandas column as a list of strings. However, my efforts to do so didn't succeed because pandas take the column value as an iterable and I get a: ValueError: Must have equal len keys and value when setting with an iterable
.
Here is an MWE
>> df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]})
>> df
col1 col2
0 1 4
1 2 5
2 3 6
>> df['new_col'] = None
>> df.loc[df.col1 == 1, 'new_col'] = ['a', 'b']
ValueError: Must have equal len keys and value when setting with an iterable
I tried to set the dtype
as list
using df.new_col = df.new_col.astype(list)
and that didn't work either.
I am wondering what would be the correct approach here.
EDIT
The answer provided here: Python pandas insert list into a cell using at
didn't work for me either.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…