When slicing 1 row of pandas, a frame fragment becomes a series

Why, when I slice a pandas data framework containing only 1 row, does the slice become a pandas series? How can I save it in a data frame?

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
0
source share
3 answers

To avoid the intermediate step of re-converting to a DataFrame, use double brackets when indexing:

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

Speed:

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

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

Use to_frame()and Tfor transposition:

df.loc[0].to_frame()

   0
a  1
b  2
c  3

and

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

   a  b  c
0  1  2  3

OR

Option # 2 uses double brackets [[]]

df.iloc[[0]]

   a  b  c
0  1  2  3
0
source

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

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

Source: https://habr.com/ru/post/1684774/


All Articles