Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

Convert column to row in Python Pandas

I have the following Python pandas dataframe:

     fruits | numFruits
---------------------
0  | apples |   10
1  | grapes |   20
2  |  figs  |   15

I want:

                 apples | grapes | figs
-----------------------------------------
Market 1 Order |    10  |   20   |  15

I have looked at pivot(), pivot_table(), Transpose and unstack() and none of them seem to give me this. Pandas newbie, so all help appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need set_index with transpose by T:

print (df.set_index('fruits').T)
fruits     apples  grapes  figs
numFruits      10      20    15

If need rename columns, it is a bit complicated:

print (df.rename(columns={'numFruits':'Market 1 Order'})
         .set_index('fruits')
         .rename_axis(None).T)
                apples  grapes  figs
Market 1 Order      10      20    15

Another faster solution is use numpy.ndarray.reshape:

print (pd.DataFrame(df.numFruits.values.reshape(1,-1), 
                    index=['Market 1 Order'], 
                    columns=df.fruits.values))

                apples  grapes  figs
Market 1 Order      10      20    15

Timings:

#[30000 rows x 2 columns] 
df = pd.concat([df]*10000).reset_index(drop=True)    
print (df)


In [55]: %timeit (pd.DataFrame([df.numFruits.values], ['Market 1 Order'], df.fruits.values))
1 loop, best of 3: 2.4 s per loop

In [56]: %timeit (pd.DataFrame(df.numFruits.values.reshape(1,-1), index=['Market 1 Order'], columns=df.fruits.values))
The slowest run took 5.64 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 424 μs per loop

In [57]: %timeit (df.rename(columns={'numFruits':'Market 1 Order'}).set_index('fruits').rename_axis(None).T)
100 loops, best of 3: 1.94 ms per loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...