Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 908
Kevin Fang Avatar asked Oct 05 '18 01:10

Kevin Fang


1 Answers

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        
like image 170
cs95 Avatar answered Oct 10 '22 12:10

cs95