67

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?

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
vaer-k
  • 10,923
  • 11
  • 42
  • 59

3 Answers3

94

You can try Series.rename:

df = pd.concat((df, s.rename('col')), axis=1)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
14

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.

vaer-k
  • 10,923
  • 11
  • 42
  • 59
8

Try:

df = pd.concat((df, s.rename('CoolColumnName')), axis=1)
piRSquared
  • 285,575
  • 57
  • 475
  • 624