Kevin Fang
Kevin Fang

Reputation: 2012

pandas add a column with only one row

This sounds a bit weird, but I think that's exactly what I needed now:

I got several pandas dataframes that contains columns with float numbers, for example:

   a  b  c
0  0  1  2
1  3  4  5
2  6  7  8

Now I want to add a column, with only one row, and the value is equal to the average of column 'a', in this case, is 3.0. So the new dataframe will looks like this:

   a  b  c  average
0  0  1  2  3.0
1  3  4  5
2  6  7  8

And all the rows below are empty.

I've tried things like df['average'] = np.mean(df['a']) but that give me a whole column of 3.0. Any help will be appreciated.

Upvotes: 9

Views: 10188

Answers (3)

cs95
cs95

Reputation: 402673

Assign a series, this is cleaner.

df['average'] = pd.Series(df['a'].mean(), index=df.index[[0]])

Or, even better, assign with loc:

df.loc[df.index[0], 'average'] = df['a'].mean().item()

Filling NaNs is straightforward, you can do

df['average'] = df['average'].fillna('')
df
   a  b  c average
0  0  1  2       3
1  3  4  5        
2  6  7  8        

Upvotes: 7

Yosi Hammer
Yosi Hammer

Reputation: 588

Here is a full example:

import pandas as pd
import numpy as np

df = pd.DataFrame(
    [(0,1,2), (3,4,5), (6,7,8)],
    columns=['a', 'b', 'c'])
print(df)

   a  b  c
0  0  1  2
1  3  4  5
2  6  7  8

df['average'] = ''
df['average'][0] = df['a'].mean()
print(df)

   a  b  c average
0  0  1  2       3
1  3  4  5        
2  6  7  8  

Upvotes: 3

U13-Forward
U13-Forward

Reputation: 71580

Can do something like:

df['average'] = [np.mean(df['a'])]+['']*(len(df)-1)

Upvotes: 3

Related Questions