如何水平获取数据帧列



我有一个名为 df 的数据帧,

   attempts       name qualify  score
a         3     Anurag     yes   12.5
b         3       Dima      no    9.0
c         2  Katherine     yes   16.5
d         3      James      no    NaN
e         2      Emily      no    9.0
f         3    Michael     yes   20.0
g         1    Matthew     yes   14.5
h         1      Laura      no    NaN
i         2      Kevin      no    8.0
j         1      Jonas     yes   19.0

通过这个'df.score'我得到了

a    12.5
b     9.0
c    16.5
d     NaN
e     9.0
f    20.0
g    14.5
h     NaN
i     8.0
j    19.0
Name: score, dtype: float64

我想要它水平

a     b    c     d    e    f     g     h    i    j
12.5  9.0  16.5  NaN  9.0  20.0  14.5  NaN  8.0  19.0

您可以只为数据帧编制索引,然后转置。请注意,您需要一个形状2d的 pandas 对象才能转置,因此在通过索引score获取pd.Series后,您可以使用to_frame()或构造函数本身构造数据帧:

df.score.to_frame().T
a    b     c   d    e     f     g   h    i     j
score  12.5  9.0  16.5 NaN  9.0  20.0  14.5 NaN  8.0  19.0

最新更新