我有以下Python pandas数据帧:
fruits | numFruits
---------------------
0 | apples | 10
1 | grapes | 20
2 | figs | 15
我想:
apples | grapes | figs
-----------------------------------------
Market 1 Order | 10 | 20 | 15
我查看了pivot(),pivot_table(),Transpose和unstack(),但似乎没有人给我这个。熊猫新手,所以非常感谢。
答案 0 :(得分:21)
print (df.set_index('fruits').T)
fruits apples grapes figs
numFruits 10 20 15
如果需要重命名列,则有点复杂:
print (df.rename(columns={'numFruits':'Market 1 Order'})
.set_index('fruits')
.rename_axis(None).T)
apples grapes figs
Market 1 Order 10 20 15
另一个更快的解决方案是使用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
<强>计时强>:
#[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
答案 1 :(得分:8)
pd.DataFrame([df.numFruits.values], ['Market 1 Order'], df.fruits.values)
apples grapes figs
Market 1 Order 10 20 15
请参阅jezrael对此概念的改进。 df.numFruits.values.reshape(1, -1)
效率更高。
答案 2 :(得分:0)
您可以按以下方式使用熊猫的转置api:
df.transpose()
将df视为您的熊猫数据框