当切片1行pandas数据帧时,切片变为一系列

gab*_*how 0 python slice dataframe pandas

为什么当我切片只包含1行的pandas数据帧时,切片会变成熊猫系列?我怎样才能保留数据帧?

df=pd.DataFrame(data=[[1,2,3]],columns=['a','b','c'])
df
Out[37]: 
   a  b  c
0  1  2  3


a=df.iloc[0]

a
Out[39]: 
a    1
b    2
c    3
Name: 0, dtype: int64
Run Code Online (Sandbox Code Playgroud)

Bra*_*mon 9

要避免重新转换回DataFrame的中间步骤,请在建立索引时使用双括号:

a = df.iloc[[0]]
print(a)
   a  b  c
0  1  2  3
Run Code Online (Sandbox Code Playgroud)

速度:

%timeit df.iloc[[0]]
192 µs per loop

%timeit df.loc[0].to_frame().T
468 µs per loop
Run Code Online (Sandbox Code Playgroud)