0

We have code that stuffs an array into a dataframe (yes, I know, not exactly best practice).

df.at[index,'alist'] = list(alist)

alist is a list but broadcasting was preventing the operation, so the list(alist) was used to prevent the broadcasting and allow the operation.

With the last set of source library updates list(alist) started broadcasting, causing this line to fail with the error, Must have equal len keys and value when setting with an ndarray

Any thoughts on how to correct?

rbinnun
  • 1,169
  • 2
  • 10
  • 18

1 Answers1

2

at won't convert you dtype for you. loc will but errors out because it assumes you are trying to push a list into multiple cells.

Convert your dtype then use at

df = pd.DataFrame(1, range(10), [*'ABC'])

df = df.astype({'A': object})

df.at[2, 'A'] = [1, 2, 3]

df

           A  B  C
0          1  1  1
1          1  1  1
2  [1, 2, 3]  1  1
3          1  1  1
4          1  1  1
5          1  1  1
6          1  1  1
7          1  1  1
8          1  1  1
9          1  1  1
​
piRSquared
  • 285,575
  • 57
  • 475
  • 624
  • [This was my suspicion as well](https://stackoverflow.com/a/54399996/4909087), but I would've imagined this would throw `ValueError: setting an array element with a sequence.` Their error message seems to suggest otherwise, but I think a dtype=object conversion should fix it anyway. – cs95 Jun 18 '19 at 15:15
  • @cs95 That's a target for this dup imo – piRSquared Jun 18 '19 at 15:21
  • Perhaps, maybe not. The fact that their error message is different from what our codes produce is still bothering me... – cs95 Jun 18 '19 at 15:22