python - When slicing a 1 row pandas dataframe the slice becomes a series -
why when slice pandas dataframe containing 1 row, slice becomes pandas series? how can keep dataframe?
df=pd.dataframe(data=[[1,2,3]],columns=['a','b','c']) df out[37]: b c 0 1 2 3 a=df.iloc[0] out[39]: 1 b 2 c 3 name: 0, dtype: int64
to avoid intermediate step of re-converting dataframe, use double brackets when indexing:
a = df.iloc[[0]] print(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
wiki
Comments
Post a Comment