When Slicing A 1 Row Pandas Dataframe The Slice Becomes A Series
Why when I slice a pandas dataframe containing only 1 row, the slice becomes a pandas series? How can I keep it a dataframe? df=pd.DataFrame(data=[[1,2,3]],columns=['a','b','c']) d
Solution 1:
To avoid the intermediate step of re-converting back to a DataFrame, use double brackets when indexing:
a = df.iloc[[0]]print(a)
a b c
0123
Speed:
%timeit df.iloc[[0]]192 µs per loop
%timeit df.loc[0].to_frame().T
468 µs per loop
Solution 2:
Solution 3:
Use to_frame()
and T
to transpose:
df.loc[0].to_frame()
0a1b2
c 3
and
df.loc[0].to_frame().Tab c
0123
OR
Option #2 use double brackets [[]]
df.iloc[[0]]
a b c
0123
Post a Comment for "When Slicing A 1 Row Pandas Dataframe The Slice Becomes A Series"