python - Create and set an element of a Pandas DataFrame to a list -
i have pandas dataframe i'm creating row-by-row (i know, know, it's not pandorable/pythonic..). i'm creating elements using .loc so
output.loc[row_id, col_id] and i'd set value empty list, [].
output.loc[row_id, col_id] = [] unfortunately, error saying size of keys , values not match (pandas thinks i'm trying set values with not to iterable).
is there way this?
thanks!
you need make sure 2 things:
- there precisely 1 entry loc,
- the column has dtype object (actually, on testing seems not issue).
a hacky way use series []:
in [11]: df = pd.dataframe([[1, 2], [3, 4]], columns=['a', 'b']) in [12]: df.loc[[0], 'a'] = pd.series([[]]) in [13]: df out[13]: b 0 [] 2 1 3 4 pandas doesn't want use [] elements because it's not efficient , makes aggregations more complicated (and un-cythonisable).
in general don't want build dataframes cell-by-cell, there (almost?) better way.
Comments
Post a Comment