concat series onto dataframe with column name

PandasDataframeRenameSeries

Pandas Problem Overview


I want to add a Series (s) to a Pandas DataFrame (df) as a new column. The series has more values than there are rows in the dataframe, so I am using the concat method along axis 1.

df = pd.concat((df, s), axis=1)

This works, but the new column of the dataframe representing the series is given an arbitrary numerical column name, and I would like this column to have a specific name instead.

Is there a way to add a series to a dataframe, when the series is longer than the rows of the dataframe, and with a specified column name in the resulting dataframe?

Pandas Solutions


Solution 1 - Pandas

You can try Series.rename:

df = pd.concat((df, s.rename('col')), axis=1)

Solution 2 - Pandas

One option is simply to specify the name when creating the series:

example_scores = pd.Series([1,2,3,4], index=['t1', 't2', 't3', 't4'], name='example_scores')

Using the name attribute when creating the series is all I needed.

Solution 3 - Pandas

Try:

df = pd.concat((df, s.rename('CoolColumnName')), axis=1)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionvaer-kView Question on Stackoverflow
Solution 1 - PandasjezraelView Answer on Stackoverflow
Solution 2 - Pandasvaer-kView Answer on Stackoverflow
Solution 3 - PandaspiRSquaredView Answer on Stackoverflow