cavosch
cavosch

Reputation: 15

append 1 Series (column) at the end of a dataframe with pandas

I am working on a notebook with python/pandas, and I have:

This is probably very simple but I am trying to append or concatenate horizontally, but I end up with dataframes with weird dimensions, at the best case I got a df with more rows (20551 rows × 20565 columns, or 20551 rows × 19 columns, full of NaNs)

EDIT: I tried:

pd.concat([X,y], axis=1)
X.append(other=y)
dfsv=[X,y]
pd.concat([X,y], axis=1, join='outer', ignore_index=False)
X.append(y, ignore_index=True)

any thoughts?

cheers!

Upvotes: 1

Views: 4883

Answers (3)

SeaBean
SeaBean

Reputation: 23217

To append a Series as a column to a dataframe, the Series must have a name which will be used as the column name. At the same time, the index of the Series need to match with the index of the dataframe. As such, you can do it this way:

y2 = pd.Series(y.values, name='y', index=X.index)
X.join(y2)

Here, we fulfill 2 prerequisites at one step by defining a Series y2 taking the values of Series y, give it the column name y and set its index to be the same as dataframe X. Then, we can use .join() to join y2 at the end of X.

Edit

Another even much simpler solution:

X['y'] = y.values

Upvotes: 1

Danail Petrov
Danail Petrov

Reputation: 1875

You can either append or con at. It is important though to specify the Axis to be columns

>>> X = pd.concat([X,Y], axis=1)

Upvotes: 0

not_speshal
not_speshal

Reputation: 23146

If X and Y have same indices:

pd.concat([X, Y], axis=1)

If X and Y have different indices, you can try:

X.append(Y, ignore_index=True)

Upvotes: 0

Related Questions