Home > Back-end >  Error while trying to store an array to dataframe cell
Error while trying to store an array to dataframe cell

Time:10-07

I am trying to store an array to the data frame cell using df.at as below:

import numpy as np
import pandas as pd

arr = np.array([[123, 123], [123, 123]], dtype=int)

df = pd.DataFrame(data= [[1, 2], [3, 4]], columns=["A", "B"])
df.at[0, "A"] = arr

But I keep getting the following error:

ValueError: setting an array element with a sequence.

I tried solving this by following this thread, but unfortunately the solutions did not work for me.

I need to use df.at and not another method, Any help ?

CodePudding user response:

It doesn't work, because you are trying to assign a NumPy array to a cell that has an integer dtype.

Try the following:

import numpy as np
import pandas as pd

a = np.array([[123, 123], [123, 123]], dtype=int)

df = pd.DataFrame(data=[[1, 2], [3, 4]], columns=["A", "B"]).astype({"A": object, "B": object})
df.at[0, "A"] = a

Result:

                          A  B
0  [[123, 123], [123, 123]]  2
1                         3  4

Be aware that your dtypes are now objects, not integers. If you only need to adjust cells in column "A", you can of course leave out "B" when changing the dtype above.

The underlying array at [0, "A"] is still of int(64) type.

CodePudding user response:

change int to object import numpy as np import pandas as pd

arr = np.array([[1, 2], [3, 4]], dtype=object)

df = pd.DataFrame(data= arr, columns=["A", "B"]) df.at[0, "A"] = arr

  • Related