Engine
Engine

Reputation: 5422

Adding column to list in python

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 ?

Upvotes: 1

Views: 3099

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210852

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])

Upvotes: 1

Related Questions