When slicing a 1 row pandas dataframe the slice becomes a series

人盡茶涼 提交于 2019-12-12 04:54:34

问题


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'])
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

回答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
0  1  2  3

Speed:

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

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



回答2:


Use to_frame() and T to transpose:

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 use double brackets [[]]

df.iloc[[0]]

   a  b  c
0  1  2  3



回答3:


Or you can slice by index

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

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


来源:https://stackoverflow.com/questions/45818612/when-slicing-a-1-row-pandas-dataframe-the-slice-becomes-a-series

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!