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

时间:2017-08-22 13:10:28

标签: python pandas dataframe slice

为什么当我切片只包含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

3 个答案:

答案 0 :(得分:7)

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

a = df.iloc[[0]]
print(a)
   a  b  c
0  1  2  3

速度:

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

%timeit df.loc[0].to_frame().T
468 µs per loop

答案 1 :(得分:0)

使用to_frame()T进行转置:

df.loc[0].to_frame()

   0
a  1
b  2
c  3

df.loc[0].to_frame().T

   a  b  c
0  1  2  3

OR

选项#2使用双括号[[]]

df.iloc[[0]]

   a  b  c
0  1  2  3

答案 2 :(得分:0)

或者您可以按索引切片

a=df.iloc[df.index==0]

a
Out[1782]: 
   a  b  c
0  1  2  3