python - set list as value in a column of a pandas dataframe -
let's have dataframe df
, create new column filled 0, use:
df['new_col'] = 0
this far, no problem. if value want use list, doesn't work:
df['new_col'] = my_list valueerror: length of values not match length of index
i understand why doesn't work (pandas trying assign 1 value of list per cell of column), how can avoid behavior? (if isn't clear every cell of new column contain same predefined list)
note: tried: df.assign(new_col = my_list)
, same problem
you'd have do:
df['new_col'] = [my_list] * len(df)
example:
in [13]: df = pd.dataframe(np.random.randn(5,3), columns=list('abc')) df out[13]: b c 0 -0.010414 1.859791 0.184692 1 -0.818050 -0.287306 -1.390080 2 -0.054434 0.106212 1.542137 3 -0.226433 0.390355 0.437592 4 -0.204653 -2.388690 0.106218 in [17]: df['b'] = [[234]] * len(df) df out[17]: b c 0 -0.010414 [234] 0.184692 1 -0.818050 [234] -1.390080 2 -0.054434 [234] 1.542137 3 -0.226433 [234] 0.437592 4 -0.204653 [234] 0.106218
note dfs optimised scalar values, storing non scalar values defeats point in opinion filtering, looking up, getting , setting become problematic point becomes pain
Comments
Post a Comment