Home > database >  Pandas: Shape of passed values is (10, 1), indices imply (10, 5) error when trying to append a dict
Pandas: Shape of passed values is (10, 1), indices imply (10, 5) error when trying to append a dict

Time:01-06

Right now I've a DataFrame that looks like this:

    A         B
0   aa       bbbb
1  aaa        bb
2   a         bb

And an array like this:

[array([0.49, 0.43, 0.06], dtype=float32),
 array([0.5, 0.47 , 0.02], dtype=float32),
 array([0.04, 0.34, 0.6], dtype=float32)]

I'd like to add this value to my original df. So I first converted my array to a dict and then I tried to append it to my original df:

mydict={}
for index, i in enumerate(array):
    mydict[index]=f"{i}"
 df_new = pd.concat([df[:3], pd.DataFrame(mydict.values(), columns=['A', 'B','C','D','E'])], ignore_index=True)

This is what I'd like to achieve:

     A     B      C     D     E
0   aa    bbbb   0.49  0.43  0.06
1  aaa     bb    0.5   0.47  0.02
2   a      bb    0.04  0.34  0.6

But this is the error I'm getting:

Shape of passed values is (10, 1), indices imply (10, 5)

CodePudding user response:

Preparing the data

import numpy as np
import pandas as pd

df = pd.DataFrame({'A': ['aa', 'aaa', 'a'], 'B': ['bbbb', 'bb', 'bb']})

array = [np.array([0.49, 0.43, 0.06], dtype=np.float32), 
 np.array([0.5, 0.47, 0.02], dtype=np.float32), 
 np.array([0.04, 0.34, 0.6], dtype=np.float32)]

You can convert the list of arrays directly to a dataframe, instead of converting it to a dictionary before converting to dataframe.

df2 = pd.DataFrame(array, columns=['C', 'D', 'E'])
pd.concat([df, df2], axis=1)


      A     B      C       D       E
0    aa  bbbb   0.49    0.43    0.06
1   aaa    bb   0.50    0.47    0.02
2     a    bb   0.04    0.34    0.60
  • Related