s5s
s5s

Reputation: 12134

Convert pandas series into a row

I calculated the means of a DatFrame which resulted in a Series object that looks like this:

means.sort_index()
0000    0.000204
0100   -0.000083
0200   -0.000260
0300   -0.000667
0400   -0.000025
0500    0.000127
0600    0.000227
0700   -0.000197
0800   -0.000497
0900   -0.000321
1000   -0.000520
1100    0.000562
1200   -0.000107
1300    0.000202
1400   -0.000445
1500    0.000665
1600    0.000288
1700   -0.000183
1800    0.000157
1900    0.000145
2000   -0.000206
2100    0.000388
2200    0.000363
2300    0.000297
dtype: float64

I'd like to add this to the DataFrame as a row but to do so, I need to convert it so that each index is a column. That is, I get a one row DataFrame with the indices as columns. I've done a pivot which results in a 24x24 matrix which I can then df.ffill().bfill() and take the first row but that is a bit dirty. means.T doesn't work either.

How would you convert the above to a 1 row DataFrame with the index as columns?

Upvotes: 9

Views: 11565

Answers (1)

jezrael
jezrael

Reputation: 862611

Use Series.to_frame for one column DataFrame and then transpose by DataFrame.T:

s = means.sort_index()
df = s.to_frame().T

Or:

df = pd.DataFrame([s.tolist()], columns=s.index)

But if want new row to DataFrame is possible use:

df.loc['avg'] = means

Or:

df.loc['avg'] = df.mean()

Upvotes: 20

Related Questions