1

I have the following list :

Training_Frame = pca.fit_transform(np_scaled_train)

with the following shape (2358,4) I want to add a fifth column, This column is saved in a pandas dataframe, for that here what I've tried without any success :

Training_Frame.append(dataframe_train.iloc[:,-1])
AttributeError: 'numpy.ndarray' object has no attribute 'append'

So I've tried the following

   saved_frame = np.append(Training_Frame,dataframe_train.iloc[:,-1])
    # This works but the result has a weird shape `(11790,)` despite :
    np.shape(dataframe_train.iloc[:,-1])  # is (2358,) so I'm expecting or hopping to get  a shape like `(2358,5)

`

So I kind of don't get what's the issue here, any Idea how could I do this ?

3
  • np.append is often misused. Learn to use np.concatenate instead. Commented May 29, 2017 at 21:20
  • 2
    Despite its name, Training_Frame is not a DataFrame; it is a numpy array. You can convert it to a DataFrame with pd.DataFrame(Training_Frame). Commented May 29, 2017 at 21:21
  • 1
    I think you need np.column_stack()... Commented May 29, 2017 at 21:21

1 Answer 1

1

if Training_Frame and dataframe_train are of the same length:

Training_Frame = np.column_stack((Training_Frame, dataframe_train.iloc[:,-1].values))

Alternatively you can generate a DataFrame from NDArray (as @ayhan suggested in the comments):

Training_Frame = pd.DataFrame(Training_Frame).assign(column_name=dataframe_train.iloc[:,-1])
Sign up to request clarification or add additional context in comments.

5 Comments

thanks for reply, I've tried your suggestion and here's what I get : IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices
@Engine, what is the output of print(type(Training_Frame))?
<class 'numpy.ndarray'>
thanks a lot for your help, I still have issue understand all datatypes in python :/. I'm using the first suggestion thanks again. I can accept ur answer in 5 min
@Engine, glad i could help :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.