[英]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? 为什么当我对仅包含1行的pandas数据框进行切片时,切片会变成pandas系列? 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
To avoid the intermediate step of re-converting back to a DataFrame, use double brackets when indexing: 为了避免重新转换回DataFrame的中间步骤,在建立索引时请使用双括号:
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
Use to_frame()
and T
to transpose: 使用to_frame()
和T
进行转置:
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 [[]]
选项#2使用双括号[[]]
df.iloc[[0]]
a b c
0 1 2 3
Or you can slice by index 或者您可以按索引切片
a=df.iloc[df.index==0]
a
Out[1782]:
a b c
0 1 2 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.